blob: 917eba444e4eb9052a06cd371a4ec2dc26d12bfa [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 Rossumf8d579c1999-01-04 18:06:45 +000033import sys
34if sys.platform == "win32":
Georg Brandl14fc4272008-05-17 18:39:55 +000035 # Attempt to configure Tcl/Tk without requiring PATH
36 from tkinter import _fix
Andrew Svetlova966c6f2012-03-21 23:52:59 +020037
38import warnings
39
Guido van Rossumf8d579c1999-01-04 18:06:45 +000040import _tkinter # If this fails your Python may not be configured for Tk
Guido van Rossum95806091997-02-15 18:33:24 +000041TclError = _tkinter.TclError
Georg Brandl14fc4272008-05-17 18:39:55 +000042from tkinter.constants import *
Guido van Rossum18468821994-06-20 07:49:28 +000043
Andrew Svetlova966c6f2012-03-21 23:52:59 +020044
Martin v. Löwis8c8aa5d2002-11-26 21:39:48 +000045wantobjects = 1
Martin v. Löwisffad6332002-11-26 09:28:05 +000046
Eric S. Raymondfc170b12001-02-09 11:51:27 +000047TkVersion = float(_tkinter.TK_VERSION)
48TclVersion = float(_tkinter.TCL_VERSION)
Guido van Rossum18468821994-06-20 07:49:28 +000049
Guido van Rossumd6615ab1997-08-05 02:35:01 +000050READABLE = _tkinter.READABLE
51WRITABLE = _tkinter.WRITABLE
52EXCEPTION = _tkinter.EXCEPTION
Guido van Rossumf53c86c1997-08-14 14:15:54 +000053
Fredrik Lundh06d28152000-08-09 18:03:12 +000054
Guido van Rossum13257902007-06-07 23:15:56 +000055def _flatten(seq):
Fredrik Lundh06d28152000-08-09 18:03:12 +000056 """Internal function."""
57 res = ()
Guido van Rossum13257902007-06-07 23:15:56 +000058 for item in seq:
59 if isinstance(item, (tuple, list)):
Fredrik Lundh06d28152000-08-09 18:03:12 +000060 res = res + _flatten(item)
61 elif item is not None:
62 res = res + (item,)
63 return res
Guido van Rossum2dcf5291994-07-06 09:23:20 +000064
Andrew M. Kuchlinge475e702000-06-18 18:45:50 +000065try: _flatten = _tkinter._flatten
66except AttributeError: pass
67
Guido van Rossum2dcf5291994-07-06 09:23:20 +000068def _cnfmerge(cnfs):
Fredrik Lundh06d28152000-08-09 18:03:12 +000069 """Internal function."""
Guido van Rossum13257902007-06-07 23:15:56 +000070 if isinstance(cnfs, dict):
Fredrik Lundh06d28152000-08-09 18:03:12 +000071 return cnfs
Guido van Rossum13257902007-06-07 23:15:56 +000072 elif isinstance(cnfs, (type(None), str)):
Fredrik Lundh06d28152000-08-09 18:03:12 +000073 return cnfs
74 else:
75 cnf = {}
76 for c in _flatten(cnfs):
77 try:
78 cnf.update(c)
Guido van Rossumb940e112007-01-10 16:19:56 +000079 except (AttributeError, TypeError) as msg:
Guido van Rossumbe19ed72007-02-09 05:37:30 +000080 print("_cnfmerge: fallback due to:", msg)
Fredrik Lundh06d28152000-08-09 18:03:12 +000081 for k, v in c.items():
82 cnf[k] = v
83 return cnf
Guido van Rossum2dcf5291994-07-06 09:23:20 +000084
Andrew M. Kuchlinge475e702000-06-18 18:45:50 +000085try: _cnfmerge = _tkinter._cnfmerge
86except AttributeError: pass
87
Guido van Rossum2dcf5291994-07-06 09:23:20 +000088class Event:
Fredrik Lundh06d28152000-08-09 18:03:12 +000089 """Container for the properties of an event.
Guido van Rossum5917ecb2000-06-29 16:30:50 +000090
Fredrik Lundh06d28152000-08-09 18:03:12 +000091 Instances of this type are generated if one of the following events occurs:
Guido van Rossum5917ecb2000-06-29 16:30:50 +000092
Fredrik Lundh06d28152000-08-09 18:03:12 +000093 KeyPress, KeyRelease - for keyboard events
94 ButtonPress, ButtonRelease, Motion, Enter, Leave, MouseWheel - for mouse events
95 Visibility, Unmap, Map, Expose, FocusIn, FocusOut, Circulate,
96 Colormap, Gravity, Reparent, Property, Destroy, Activate,
97 Deactivate - for window events.
98
99 If a callback function for one of these events is registered
100 using bind, bind_all, bind_class, or tag_bind, the callback is
101 called with an Event as first argument. It will have the
102 following attributes (in braces are the event types for which
103 the attribute is valid):
104
Guido van Rossum5917ecb2000-06-29 16:30:50 +0000105 serial - serial number of event
Fredrik Lundh06d28152000-08-09 18:03:12 +0000106 num - mouse button pressed (ButtonPress, ButtonRelease)
107 focus - whether the window has the focus (Enter, Leave)
108 height - height of the exposed window (Configure, Expose)
109 width - width of the exposed window (Configure, Expose)
110 keycode - keycode of the pressed key (KeyPress, KeyRelease)
111 state - state of the event as a number (ButtonPress, ButtonRelease,
112 Enter, KeyPress, KeyRelease,
113 Leave, Motion)
114 state - state as a string (Visibility)
115 time - when the event occurred
116 x - x-position of the mouse
117 y - y-position of the mouse
118 x_root - x-position of the mouse on the screen
119 (ButtonPress, ButtonRelease, KeyPress, KeyRelease, Motion)
120 y_root - y-position of the mouse on the screen
121 (ButtonPress, ButtonRelease, KeyPress, KeyRelease, Motion)
122 char - pressed character (KeyPress, KeyRelease)
123 send_event - see X/Windows documentation
Walter Dörwald966c2642005-11-09 17:12:43 +0000124 keysym - keysym of the event as a string (KeyPress, KeyRelease)
Fredrik Lundh06d28152000-08-09 18:03:12 +0000125 keysym_num - keysym of the event as a number (KeyPress, KeyRelease)
126 type - type of the event as a number
127 widget - widget in which the event occurred
128 delta - delta of wheel movement (MouseWheel)
129 """
130 pass
Guido van Rossum2dcf5291994-07-06 09:23:20 +0000131
Guido van Rossumc4570481998-03-20 20:45:49 +0000132_support_default_root = 1
Guido van Rossumaec5dc91994-06-27 07:55:12 +0000133_default_root = None
134
Guido van Rossumc4570481998-03-20 20:45:49 +0000135def NoDefaultRoot():
Fredrik Lundh06d28152000-08-09 18:03:12 +0000136 """Inhibit setting of default root window.
Guido van Rossum5917ecb2000-06-29 16:30:50 +0000137
Fredrik Lundh06d28152000-08-09 18:03:12 +0000138 Call this function to inhibit that the first instance of
139 Tk is used for windows without an explicit parent window.
140 """
141 global _support_default_root
142 _support_default_root = 0
143 global _default_root
144 _default_root = None
145 del _default_root
Guido van Rossumc4570481998-03-20 20:45:49 +0000146
Guido van Rossum45853db1994-06-20 12:19:19 +0000147def _tkerror(err):
Fredrik Lundh06d28152000-08-09 18:03:12 +0000148 """Internal function."""
149 pass
Guido van Rossum18468821994-06-20 07:49:28 +0000150
Guido van Rossum97aeca11994-07-07 13:12:12 +0000151def _exit(code='0'):
Fredrik Lundh06d28152000-08-09 18:03:12 +0000152 """Internal function. Calling it will throw the exception SystemExit."""
Collin Winterce36ad82007-08-30 01:19:48 +0000153 raise SystemExit(code)
Guido van Rossum97aeca11994-07-07 13:12:12 +0000154
Guido van Rossumaec5dc91994-06-27 07:55:12 +0000155_varnum = 0
156class Variable:
Guido van Rossum2cd0a652003-04-16 20:10:03 +0000157 """Class to define value holders for e.g. buttons.
158
159 Subclasses StringVar, IntVar, DoubleVar, BooleanVar are specializations
160 that constrain the type of the value returned from get()."""
Fredrik Lundh06d28152000-08-09 18:03:12 +0000161 _default = ""
Martin v. Löwis2b695a42012-03-12 17:47:35 -0700162 _tk = None
Thomas Wouters0e3f5912006-08-11 14:57:12 +0000163 def __init__(self, master=None, value=None, name=None):
164 """Construct a variable
165
166 MASTER can be given as master widget.
167 VALUE is an optional value (defaults to "")
168 NAME is an optional Tcl name (defaults to PY_VARnum).
169
170 If NAME matches an existing variable and VALUE is omitted
171 then the existing value is retained.
Fredrik Lundh06d28152000-08-09 18:03:12 +0000172 """
Martin v. Löwis2b695a42012-03-12 17:47:35 -0700173 # check for type of NAME parameter to override weird error message
174 # raised from Modules/_tkinter.c:SetVar like:
175 # TypeError: setvar() takes exactly 3 arguments (2 given)
176 if name is not None and not isinstance(name, str):
177 raise TypeError("name must be a string")
Fredrik Lundh06d28152000-08-09 18:03:12 +0000178 global _varnum
179 if not master:
180 master = _default_root
181 self._master = master
182 self._tk = master.tk
Thomas Wouters0e3f5912006-08-11 14:57:12 +0000183 if name:
184 self._name = name
185 else:
186 self._name = 'PY_VAR' + repr(_varnum)
187 _varnum += 1
Benjamin Peterson2a691a82008-03-31 01:51:45 +0000188 if value is not None:
Martin v. Löwis2b695a42012-03-12 17:47:35 -0700189 self.initialize(value)
Thomas Wouters0e3f5912006-08-11 14:57:12 +0000190 elif not self._tk.call("info", "exists", self._name):
Martin v. Löwis2b695a42012-03-12 17:47:35 -0700191 self.initialize(self._default)
Fredrik Lundh06d28152000-08-09 18:03:12 +0000192 def __del__(self):
193 """Unset the variable in Tcl."""
Martin v. Löwis2b695a42012-03-12 17:47:35 -0700194 if (self._tk is not None and self._tk.call("info", "exists",
195 self._name)):
196 self._tk.globalunsetvar(self._name)
Fredrik Lundh06d28152000-08-09 18:03:12 +0000197 def __str__(self):
198 """Return the name of the variable in Tcl."""
199 return self._name
200 def set(self, value):
201 """Set the variable to VALUE."""
202 return self._tk.globalsetvar(self._name, value)
Martin v. Löwis2b695a42012-03-12 17:47:35 -0700203 initialize = set
Guido van Rossum2cd0a652003-04-16 20:10:03 +0000204 def get(self):
205 """Return value of variable."""
206 return self._tk.globalgetvar(self._name)
Fredrik Lundh06d28152000-08-09 18:03:12 +0000207 def trace_variable(self, mode, callback):
208 """Define a trace callback for the variable.
Guido van Rossum5917ecb2000-06-29 16:30:50 +0000209
Fredrik Lundh06d28152000-08-09 18:03:12 +0000210 MODE is one of "r", "w", "u" for read, write, undefine.
211 CALLBACK must be a function which is called when
212 the variable is read, written or undefined.
Guido van Rossum5917ecb2000-06-29 16:30:50 +0000213
Fredrik Lundh06d28152000-08-09 18:03:12 +0000214 Return the name of the callback.
215 """
216 cbname = self._master._register(callback)
217 self._tk.call("trace", "variable", self._name, mode, cbname)
218 return cbname
219 trace = trace_variable
220 def trace_vdelete(self, mode, cbname):
221 """Delete the trace callback for a variable.
Guido van Rossum5917ecb2000-06-29 16:30:50 +0000222
Fredrik Lundh06d28152000-08-09 18:03:12 +0000223 MODE is one of "r", "w", "u" for read, write, undefine.
224 CBNAME is the name of the callback returned from trace_variable or trace.
225 """
226 self._tk.call("trace", "vdelete", self._name, mode, cbname)
227 self._master.deletecommand(cbname)
228 def trace_vinfo(self):
229 """Return all trace callback information."""
Alexander Belopolsky022f0492010-11-22 19:40:51 +0000230 return [self._tk.split(x) for x in self._tk.splitlist(
231 self._tk.call("trace", "vinfo", self._name))]
Thomas Wouters0e3f5912006-08-11 14:57:12 +0000232 def __eq__(self, other):
233 """Comparison for equality (==).
234
235 Note: if the Variable's master matters to behavior
236 also compare self._master == other._master
237 """
238 return self.__class__.__name__ == other.__class__.__name__ \
239 and self._name == other._name
Guido van Rossumaec5dc91994-06-27 07:55:12 +0000240
241class StringVar(Variable):
Fredrik Lundh06d28152000-08-09 18:03:12 +0000242 """Value holder for strings variables."""
243 _default = ""
Thomas Wouters0e3f5912006-08-11 14:57:12 +0000244 def __init__(self, master=None, value=None, name=None):
Fredrik Lundh06d28152000-08-09 18:03:12 +0000245 """Construct a string variable.
Guido van Rossum5917ecb2000-06-29 16:30:50 +0000246
Thomas Wouters0e3f5912006-08-11 14:57:12 +0000247 MASTER can be given as master widget.
248 VALUE is an optional value (defaults to "")
249 NAME is an optional Tcl name (defaults to PY_VARnum).
250
251 If NAME matches an existing variable and VALUE is omitted
252 then the existing value is retained.
253 """
254 Variable.__init__(self, master, value, name)
Guido van Rossum5917ecb2000-06-29 16:30:50 +0000255
Fredrik Lundh06d28152000-08-09 18:03:12 +0000256 def get(self):
257 """Return value of variable as string."""
Martin v. Löwisbfe175c2003-04-16 19:42:51 +0000258 value = self._tk.globalgetvar(self._name)
Guido van Rossum3172c5d2007-10-16 18:12:55 +0000259 if isinstance(value, str):
Martin v. Löwisbfe175c2003-04-16 19:42:51 +0000260 return value
261 return str(value)
Guido van Rossumaec5dc91994-06-27 07:55:12 +0000262
263class IntVar(Variable):
Fredrik Lundh06d28152000-08-09 18:03:12 +0000264 """Value holder for integer variables."""
265 _default = 0
Thomas Wouters0e3f5912006-08-11 14:57:12 +0000266 def __init__(self, master=None, value=None, name=None):
Fredrik Lundh06d28152000-08-09 18:03:12 +0000267 """Construct an integer variable.
Guido van Rossum5917ecb2000-06-29 16:30:50 +0000268
Thomas Wouters0e3f5912006-08-11 14:57:12 +0000269 MASTER can be given as master widget.
270 VALUE is an optional value (defaults to 0)
271 NAME is an optional Tcl name (defaults to PY_VARnum).
272
273 If NAME matches an existing variable and VALUE is omitted
274 then the existing value is retained.
275 """
276 Variable.__init__(self, master, value, name)
Guido van Rossum5917ecb2000-06-29 16:30:50 +0000277
Fredrik Lundh06d28152000-08-09 18:03:12 +0000278 def get(self):
279 """Return the value of the variable as an integer."""
280 return getint(self._tk.globalgetvar(self._name))
Guido van Rossumaec5dc91994-06-27 07:55:12 +0000281
282class DoubleVar(Variable):
Fredrik Lundh06d28152000-08-09 18:03:12 +0000283 """Value holder for float variables."""
284 _default = 0.0
Thomas Wouters0e3f5912006-08-11 14:57:12 +0000285 def __init__(self, master=None, value=None, name=None):
Fredrik Lundh06d28152000-08-09 18:03:12 +0000286 """Construct a float variable.
Guido van Rossum5917ecb2000-06-29 16:30:50 +0000287
Thomas Wouters0e3f5912006-08-11 14:57:12 +0000288 MASTER can be given as master widget.
289 VALUE is an optional value (defaults to 0.0)
290 NAME is an optional Tcl name (defaults to PY_VARnum).
291
292 If NAME matches an existing variable and VALUE is omitted
293 then the existing value is retained.
294 """
295 Variable.__init__(self, master, value, name)
Fredrik Lundh06d28152000-08-09 18:03:12 +0000296
297 def get(self):
298 """Return the value of the variable as a float."""
299 return getdouble(self._tk.globalgetvar(self._name))
Guido van Rossumaec5dc91994-06-27 07:55:12 +0000300
301class BooleanVar(Variable):
Fredrik Lundh06d28152000-08-09 18:03:12 +0000302 """Value holder for boolean variables."""
Thomas Wouters0e3f5912006-08-11 14:57:12 +0000303 _default = False
304 def __init__(self, master=None, value=None, name=None):
Fredrik Lundh06d28152000-08-09 18:03:12 +0000305 """Construct a boolean variable.
Guido van Rossum5917ecb2000-06-29 16:30:50 +0000306
Thomas Wouters0e3f5912006-08-11 14:57:12 +0000307 MASTER can be given as master widget.
308 VALUE is an optional value (defaults to False)
309 NAME is an optional Tcl name (defaults to PY_VARnum).
310
311 If NAME matches an existing variable and VALUE is omitted
312 then the existing value is retained.
313 """
314 Variable.__init__(self, master, value, name)
Guido van Rossum5917ecb2000-06-29 16:30:50 +0000315
Fredrik Lundh06d28152000-08-09 18:03:12 +0000316 def get(self):
Martin v. Löwisbfe175c2003-04-16 19:42:51 +0000317 """Return the value of the variable as a bool."""
Martin v. Löwis2b695a42012-03-12 17:47:35 -0700318 try:
319 return self._tk.getboolean(self._tk.globalgetvar(self._name))
320 except TclError:
321 raise ValueError("invalid literal for getboolean()")
Guido van Rossumaec5dc91994-06-27 07:55:12 +0000322
Guido van Rossum35f67fb1995-08-04 03:50:29 +0000323def mainloop(n=0):
Fredrik Lundh06d28152000-08-09 18:03:12 +0000324 """Run the main loop of Tcl."""
325 _default_root.tk.mainloop(n)
Guido van Rossum2dcf5291994-07-06 09:23:20 +0000326
Guido van Rossum0132f691998-04-30 17:50:36 +0000327getint = int
Guido van Rossum2dcf5291994-07-06 09:23:20 +0000328
Guido van Rossum0132f691998-04-30 17:50:36 +0000329getdouble = float
Guido van Rossum2dcf5291994-07-06 09:23:20 +0000330
331def getboolean(s):
Fredrik Lundh06d28152000-08-09 18:03:12 +0000332 """Convert true and false to integer values 1 and 0."""
Martin v. Löwis2b695a42012-03-12 17:47:35 -0700333 try:
334 return _default_root.tk.getboolean(s)
335 except TclError:
336 raise ValueError("invalid literal for getboolean()")
Guido van Rossum2dcf5291994-07-06 09:23:20 +0000337
Guido van Rossum368e06b1997-11-07 20:38:49 +0000338# Methods defined on both toplevel and interior widgets
Guido van Rossum18468821994-06-20 07:49:28 +0000339class Misc:
Fredrik Lundh06d28152000-08-09 18:03:12 +0000340 """Internal class.
Guido van Rossum5917ecb2000-06-29 16:30:50 +0000341
Fredrik Lundh06d28152000-08-09 18:03:12 +0000342 Base class which defines methods common for interior widgets."""
Guido van Rossum5917ecb2000-06-29 16:30:50 +0000343
Fredrik Lundh06d28152000-08-09 18:03:12 +0000344 # XXX font command?
345 _tclCommands = None
346 def destroy(self):
347 """Internal function.
Guido van Rossum5917ecb2000-06-29 16:30:50 +0000348
Fredrik Lundh06d28152000-08-09 18:03:12 +0000349 Delete all Tcl commands created for
350 this widget in the Tcl interpreter."""
351 if self._tclCommands is not None:
352 for name in self._tclCommands:
353 #print '- Tkinter: deleted command', name
354 self.tk.deletecommand(name)
355 self._tclCommands = None
356 def deletecommand(self, name):
357 """Internal function.
Guido van Rossum5917ecb2000-06-29 16:30:50 +0000358
Fredrik Lundh06d28152000-08-09 18:03:12 +0000359 Delete the Tcl command provided in NAME."""
360 #print '- Tkinter: deleted command', name
361 self.tk.deletecommand(name)
362 try:
363 self._tclCommands.remove(name)
364 except ValueError:
365 pass
366 def tk_strictMotif(self, boolean=None):
367 """Set Tcl internal variable, whether the look and feel
368 should adhere to Motif.
Guido van Rossum5917ecb2000-06-29 16:30:50 +0000369
Fredrik Lundh06d28152000-08-09 18:03:12 +0000370 A parameter of 1 means adhere to Motif (e.g. no color
371 change if mouse passes over slider).
372 Returns the set value."""
373 return self.tk.getboolean(self.tk.call(
374 'set', 'tk_strictMotif', boolean))
375 def tk_bisque(self):
376 """Change the color scheme to light brown as used in Tk 3.6 and before."""
377 self.tk.call('tk_bisque')
378 def tk_setPalette(self, *args, **kw):
379 """Set a new color scheme for all widget elements.
Guido van Rossum5917ecb2000-06-29 16:30:50 +0000380
Fredrik Lundh06d28152000-08-09 18:03:12 +0000381 A single color as argument will cause that all colors of Tk
382 widget elements are derived from this.
383 Alternatively several keyword parameters and its associated
384 colors can be given. The following keywords are valid:
385 activeBackground, foreground, selectColor,
386 activeForeground, highlightBackground, selectBackground,
387 background, highlightColor, selectForeground,
388 disabledForeground, insertBackground, troughColor."""
389 self.tk.call(('tk_setPalette',)
390 + _flatten(args) + _flatten(kw.items()))
391 def tk_menuBar(self, *args):
392 """Do not use. Needed in Tk 3.6 and earlier."""
393 pass # obsolete since Tk 4.0
394 def wait_variable(self, name='PY_VAR'):
395 """Wait until the variable is modified.
Guido van Rossum5917ecb2000-06-29 16:30:50 +0000396
Fredrik Lundh06d28152000-08-09 18:03:12 +0000397 A parameter of type IntVar, StringVar, DoubleVar or
398 BooleanVar must be given."""
399 self.tk.call('tkwait', 'variable', name)
400 waitvar = wait_variable # XXX b/w compat
401 def wait_window(self, window=None):
402 """Wait until a WIDGET is destroyed.
Guido van Rossum5917ecb2000-06-29 16:30:50 +0000403
Fredrik Lundh06d28152000-08-09 18:03:12 +0000404 If no parameter is given self is used."""
Fred Drake132dce22000-12-12 23:11:42 +0000405 if window is None:
Fredrik Lundh06d28152000-08-09 18:03:12 +0000406 window = self
407 self.tk.call('tkwait', 'window', window._w)
408 def wait_visibility(self, window=None):
409 """Wait until the visibility of a WIDGET changes
410 (e.g. it appears).
Guido van Rossum5917ecb2000-06-29 16:30:50 +0000411
Fredrik Lundh06d28152000-08-09 18:03:12 +0000412 If no parameter is given self is used."""
Fred Drake132dce22000-12-12 23:11:42 +0000413 if window is None:
Fredrik Lundh06d28152000-08-09 18:03:12 +0000414 window = self
415 self.tk.call('tkwait', 'visibility', window._w)
416 def setvar(self, name='PY_VAR', value='1'):
417 """Set Tcl variable NAME to VALUE."""
418 self.tk.setvar(name, value)
419 def getvar(self, name='PY_VAR'):
420 """Return value of Tcl variable NAME."""
421 return self.tk.getvar(name)
422 getint = int
423 getdouble = float
424 def getboolean(self, s):
Neal Norwitz6e5be222003-04-17 13:13:55 +0000425 """Return a boolean value for Tcl boolean values true and false given as parameter."""
Martin v. Löwis2b695a42012-03-12 17:47:35 -0700426 try:
427 return self.tk.getboolean(s)
428 except TclError:
429 raise ValueError("invalid literal for getboolean()")
Fredrik Lundh06d28152000-08-09 18:03:12 +0000430 def focus_set(self):
431 """Direct input focus to this widget.
Guido van Rossum5917ecb2000-06-29 16:30:50 +0000432
Fredrik Lundh06d28152000-08-09 18:03:12 +0000433 If the application currently does not have the focus
434 this widget will get the focus if the application gets
435 the focus through the window manager."""
436 self.tk.call('focus', self._w)
437 focus = focus_set # XXX b/w compat?
438 def focus_force(self):
439 """Direct input focus to this widget even if the
440 application does not have the focus. Use with
441 caution!"""
442 self.tk.call('focus', '-force', self._w)
443 def focus_get(self):
444 """Return the widget which has currently the focus in the
445 application.
Guido van Rossum5917ecb2000-06-29 16:30:50 +0000446
Fredrik Lundh06d28152000-08-09 18:03:12 +0000447 Use focus_displayof to allow working with several
448 displays. Return None if application does not have
449 the focus."""
450 name = self.tk.call('focus')
451 if name == 'none' or not name: return None
452 return self._nametowidget(name)
453 def focus_displayof(self):
454 """Return the widget which has currently the focus on the
455 display where this widget is located.
Guido van Rossum5917ecb2000-06-29 16:30:50 +0000456
Fredrik Lundh06d28152000-08-09 18:03:12 +0000457 Return None if the application does not have the focus."""
458 name = self.tk.call('focus', '-displayof', self._w)
459 if name == 'none' or not name: return None
460 return self._nametowidget(name)
461 def focus_lastfor(self):
462 """Return the widget which would have the focus if top level
463 for this widget gets the focus from the window manager."""
464 name = self.tk.call('focus', '-lastfor', self._w)
465 if name == 'none' or not name: return None
466 return self._nametowidget(name)
467 def tk_focusFollowsMouse(self):
468 """The widget under mouse will get automatically focus. Can not
469 be disabled easily."""
470 self.tk.call('tk_focusFollowsMouse')
471 def tk_focusNext(self):
472 """Return the next widget in the focus order which follows
473 widget which has currently the focus.
Guido van Rossum5917ecb2000-06-29 16:30:50 +0000474
Fredrik Lundh06d28152000-08-09 18:03:12 +0000475 The focus order first goes to the next child, then to
476 the children of the child recursively and then to the
477 next sibling which is higher in the stacking order. A
478 widget is omitted if it has the takefocus resource set
479 to 0."""
480 name = self.tk.call('tk_focusNext', self._w)
481 if not name: return None
482 return self._nametowidget(name)
483 def tk_focusPrev(self):
484 """Return previous widget in the focus order. See tk_focusNext for details."""
485 name = self.tk.call('tk_focusPrev', self._w)
486 if not name: return None
487 return self._nametowidget(name)
488 def after(self, ms, func=None, *args):
489 """Call function once after given time.
Guido van Rossum5917ecb2000-06-29 16:30:50 +0000490
Fredrik Lundh06d28152000-08-09 18:03:12 +0000491 MS specifies the time in milliseconds. FUNC gives the
492 function which shall be called. Additional parameters
493 are given as parameters to the function call. Return
494 identifier to cancel scheduling with after_cancel."""
495 if not func:
496 # I'd rather use time.sleep(ms*0.001)
497 self.tk.call('after', ms)
498 else:
Thomas Wouters49fd7fa2006-04-21 10:40:58 +0000499 def callit():
Fredrik Lundh06d28152000-08-09 18:03:12 +0000500 try:
Raymond Hettingerff41c482003-04-06 09:01:11 +0000501 func(*args)
Fredrik Lundh06d28152000-08-09 18:03:12 +0000502 finally:
503 try:
Thomas Wouters49fd7fa2006-04-21 10:40:58 +0000504 self.deletecommand(name)
Fredrik Lundh06d28152000-08-09 18:03:12 +0000505 except TclError:
506 pass
507 name = self._register(callit)
Fredrik Lundh06d28152000-08-09 18:03:12 +0000508 return self.tk.call('after', ms, name)
509 def after_idle(self, func, *args):
510 """Call FUNC once if the Tcl main loop has no event to
511 process.
Guido van Rossum5917ecb2000-06-29 16:30:50 +0000512
Fredrik Lundh06d28152000-08-09 18:03:12 +0000513 Return an identifier to cancel the scheduling with
514 after_cancel."""
Raymond Hettingerff41c482003-04-06 09:01:11 +0000515 return self.after('idle', func, *args)
Fredrik Lundh06d28152000-08-09 18:03:12 +0000516 def after_cancel(self, id):
517 """Cancel scheduling of function identified with ID.
Guido van Rossum5917ecb2000-06-29 16:30:50 +0000518
Fredrik Lundh06d28152000-08-09 18:03:12 +0000519 Identifier returned by after or after_idle must be
520 given as first parameter."""
Martin v. Löwis0f9e5252003-06-07 19:52:38 +0000521 try:
Neal Norwitz3c0f2c92003-07-01 21:12:47 +0000522 data = self.tk.call('after', 'info', id)
523 # In Tk 8.3, splitlist returns: (script, type)
524 # In Tk 8.4, splitlist may return (script, type) or (script,)
525 script = self.tk.splitlist(data)[0]
Martin v. Löwis0f9e5252003-06-07 19:52:38 +0000526 self.deletecommand(script)
527 except TclError:
528 pass
Fredrik Lundh06d28152000-08-09 18:03:12 +0000529 self.tk.call('after', 'cancel', id)
530 def bell(self, displayof=0):
531 """Ring a display's bell."""
532 self.tk.call(('bell',) + self._displayof(displayof))
Thomas Wouters49fd7fa2006-04-21 10:40:58 +0000533
Fredrik Lundh06d28152000-08-09 18:03:12 +0000534 # Clipboard handling:
Thomas Wouters49fd7fa2006-04-21 10:40:58 +0000535 def clipboard_get(self, **kw):
536 """Retrieve data from the clipboard on window's display.
537
538 The window keyword defaults to the root window of the Tkinter
539 application.
540
541 The type keyword specifies the form in which the data is
542 to be returned and should be an atom name such as STRING
Ned Deily4d377d92012-05-15 18:08:11 -0700543 or FILE_NAME. Type defaults to STRING, except on X11, where the default
544 is to try UTF8_STRING and fall back to STRING.
Thomas Wouters49fd7fa2006-04-21 10:40:58 +0000545
546 This command is equivalent to:
547
548 selection_get(CLIPBOARD)
549 """
Ned Deily4d377d92012-05-15 18:08:11 -0700550 if 'type' not in kw and self._windowingsystem == 'x11':
551 try:
552 kw['type'] = 'UTF8_STRING'
553 return self.tk.call(('clipboard', 'get') + self._options(kw))
554 except TclError:
555 del kw['type']
Thomas Wouters49fd7fa2006-04-21 10:40:58 +0000556 return self.tk.call(('clipboard', 'get') + self._options(kw))
557
Fredrik Lundh06d28152000-08-09 18:03:12 +0000558 def clipboard_clear(self, **kw):
559 """Clear the data in the Tk clipboard.
Guido van Rossum5917ecb2000-06-29 16:30:50 +0000560
Fredrik Lundh06d28152000-08-09 18:03:12 +0000561 A widget specified for the optional displayof keyword
562 argument specifies the target display."""
Guido van Rossume014a132006-08-19 16:53:45 +0000563 if 'displayof' not in kw: kw['displayof'] = self._w
Fredrik Lundh06d28152000-08-09 18:03:12 +0000564 self.tk.call(('clipboard', 'clear') + self._options(kw))
565 def clipboard_append(self, string, **kw):
566 """Append STRING to the Tk clipboard.
Guido van Rossum5917ecb2000-06-29 16:30:50 +0000567
Fredrik Lundh06d28152000-08-09 18:03:12 +0000568 A widget specified at the optional displayof keyword
569 argument specifies the target display. The clipboard
570 can be retrieved with selection_get."""
Guido van Rossume014a132006-08-19 16:53:45 +0000571 if 'displayof' not in kw: kw['displayof'] = self._w
Fredrik Lundh06d28152000-08-09 18:03:12 +0000572 self.tk.call(('clipboard', 'append') + self._options(kw)
573 + ('--', string))
574 # XXX grab current w/o window argument
575 def grab_current(self):
576 """Return widget which has currently the grab in this application
577 or None."""
578 name = self.tk.call('grab', 'current', self._w)
579 if not name: return None
580 return self._nametowidget(name)
581 def grab_release(self):
582 """Release grab for this widget if currently set."""
583 self.tk.call('grab', 'release', self._w)
584 def grab_set(self):
585 """Set grab for this widget.
Guido van Rossum5917ecb2000-06-29 16:30:50 +0000586
Fredrik Lundh06d28152000-08-09 18:03:12 +0000587 A grab directs all events to this and descendant
588 widgets in the application."""
589 self.tk.call('grab', 'set', self._w)
590 def grab_set_global(self):
591 """Set global grab for this widget.
Guido van Rossum5917ecb2000-06-29 16:30:50 +0000592
Fredrik Lundh06d28152000-08-09 18:03:12 +0000593 A global grab directs all events to this and
594 descendant widgets on the display. Use with caution -
595 other applications do not get events anymore."""
596 self.tk.call('grab', 'set', '-global', self._w)
597 def grab_status(self):
598 """Return None, "local" or "global" if this widget has
599 no, a local or a global grab."""
600 status = self.tk.call('grab', 'status', self._w)
601 if status == 'none': status = None
602 return status
Fredrik Lundh06d28152000-08-09 18:03:12 +0000603 def option_add(self, pattern, value, priority = None):
604 """Set a VALUE (second parameter) for an option
605 PATTERN (first parameter).
Guido van Rossum5917ecb2000-06-29 16:30:50 +0000606
Fredrik Lundh06d28152000-08-09 18:03:12 +0000607 An optional third parameter gives the numeric priority
608 (defaults to 80)."""
609 self.tk.call('option', 'add', pattern, value, priority)
610 def option_clear(self):
611 """Clear the option database.
Guido van Rossum5917ecb2000-06-29 16:30:50 +0000612
Fredrik Lundh06d28152000-08-09 18:03:12 +0000613 It will be reloaded if option_add is called."""
614 self.tk.call('option', 'clear')
615 def option_get(self, name, className):
616 """Return the value for an option NAME for this widget
617 with CLASSNAME.
Guido van Rossum5917ecb2000-06-29 16:30:50 +0000618
Fredrik Lundh06d28152000-08-09 18:03:12 +0000619 Values with higher priority override lower values."""
620 return self.tk.call('option', 'get', self._w, name, className)
621 def option_readfile(self, fileName, priority = None):
622 """Read file FILENAME into the option database.
Guido van Rossum5917ecb2000-06-29 16:30:50 +0000623
Fredrik Lundh06d28152000-08-09 18:03:12 +0000624 An optional second parameter gives the numeric
625 priority."""
626 self.tk.call('option', 'readfile', fileName, priority)
627 def selection_clear(self, **kw):
628 """Clear the current X selection."""
Guido van Rossume014a132006-08-19 16:53:45 +0000629 if 'displayof' not in kw: kw['displayof'] = self._w
Fredrik Lundh06d28152000-08-09 18:03:12 +0000630 self.tk.call(('selection', 'clear') + self._options(kw))
631 def selection_get(self, **kw):
632 """Return the contents of the current X selection.
Guido van Rossum5917ecb2000-06-29 16:30:50 +0000633
Fredrik Lundh06d28152000-08-09 18:03:12 +0000634 A keyword parameter selection specifies the name of
635 the selection and defaults to PRIMARY. A keyword
636 parameter displayof specifies a widget on the display
Ned Deily4d377d92012-05-15 18:08:11 -0700637 to use. A keyword parameter type specifies the form of data to be
638 fetched, defaulting to STRING except on X11, where UTF8_STRING is tried
639 before STRING."""
Guido van Rossume014a132006-08-19 16:53:45 +0000640 if 'displayof' not in kw: kw['displayof'] = self._w
Ned Deily4d377d92012-05-15 18:08:11 -0700641 if 'type' not in kw and self._windowingsystem == 'x11':
642 try:
643 kw['type'] = 'UTF8_STRING'
644 return self.tk.call(('selection', 'get') + self._options(kw))
645 except TclError:
646 del kw['type']
Fredrik Lundh06d28152000-08-09 18:03:12 +0000647 return self.tk.call(('selection', 'get') + self._options(kw))
648 def selection_handle(self, command, **kw):
649 """Specify a function COMMAND to call if the X
650 selection owned by this widget is queried by another
651 application.
Guido van Rossum5917ecb2000-06-29 16:30:50 +0000652
Fredrik Lundh06d28152000-08-09 18:03:12 +0000653 This function must return the contents of the
654 selection. The function will be called with the
655 arguments OFFSET and LENGTH which allows the chunking
656 of very long selections. The following keyword
657 parameters can be provided:
658 selection - name of the selection (default PRIMARY),
659 type - type of the selection (e.g. STRING, FILE_NAME)."""
660 name = self._register(command)
661 self.tk.call(('selection', 'handle') + self._options(kw)
662 + (self._w, name))
663 def selection_own(self, **kw):
664 """Become owner of X selection.
Guido van Rossum5917ecb2000-06-29 16:30:50 +0000665
Fredrik Lundh06d28152000-08-09 18:03:12 +0000666 A keyword parameter selection specifies the name of
667 the selection (default PRIMARY)."""
668 self.tk.call(('selection', 'own') +
669 self._options(kw) + (self._w,))
670 def selection_own_get(self, **kw):
671 """Return owner of X selection.
Guido van Rossum5917ecb2000-06-29 16:30:50 +0000672
Fredrik Lundh06d28152000-08-09 18:03:12 +0000673 The following keyword parameter can
674 be provided:
675 selection - name of the selection (default PRIMARY),
676 type - type of the selection (e.g. STRING, FILE_NAME)."""
Guido van Rossume014a132006-08-19 16:53:45 +0000677 if 'displayof' not in kw: kw['displayof'] = self._w
Fredrik Lundh06d28152000-08-09 18:03:12 +0000678 name = self.tk.call(('selection', 'own') + self._options(kw))
679 if not name: return None
680 return self._nametowidget(name)
681 def send(self, interp, cmd, *args):
682 """Send Tcl command CMD to different interpreter INTERP to be executed."""
683 return self.tk.call(('send', interp, cmd) + args)
684 def lower(self, belowThis=None):
685 """Lower this widget in the stacking order."""
686 self.tk.call('lower', self._w, belowThis)
687 def tkraise(self, aboveThis=None):
688 """Raise this widget in the stacking order."""
689 self.tk.call('raise', self._w, aboveThis)
690 lift = tkraise
691 def colormodel(self, value=None):
692 """Useless. Not implemented in Tk."""
693 return self.tk.call('tk', 'colormodel', self._w, value)
694 def winfo_atom(self, name, displayof=0):
695 """Return integer which represents atom NAME."""
696 args = ('winfo', 'atom') + self._displayof(displayof) + (name,)
697 return getint(self.tk.call(args))
698 def winfo_atomname(self, id, displayof=0):
699 """Return name of atom with identifier ID."""
700 args = ('winfo', 'atomname') \
701 + self._displayof(displayof) + (id,)
702 return self.tk.call(args)
703 def winfo_cells(self):
704 """Return number of cells in the colormap for this widget."""
705 return getint(
706 self.tk.call('winfo', 'cells', self._w))
707 def winfo_children(self):
708 """Return a list of all widgets which are children of this widget."""
Martin v. Löwisf2041b82002-03-27 17:15:57 +0000709 result = []
710 for child in self.tk.splitlist(
711 self.tk.call('winfo', 'children', self._w)):
712 try:
713 # Tcl sometimes returns extra windows, e.g. for
714 # menus; those need to be skipped
715 result.append(self._nametowidget(child))
716 except KeyError:
717 pass
718 return result
719
Fredrik Lundh06d28152000-08-09 18:03:12 +0000720 def winfo_class(self):
721 """Return window class name of this widget."""
722 return self.tk.call('winfo', 'class', self._w)
723 def winfo_colormapfull(self):
724 """Return true if at the last color request the colormap was full."""
725 return self.tk.getboolean(
726 self.tk.call('winfo', 'colormapfull', self._w))
727 def winfo_containing(self, rootX, rootY, displayof=0):
728 """Return the widget which is at the root coordinates ROOTX, ROOTY."""
729 args = ('winfo', 'containing') \
730 + self._displayof(displayof) + (rootX, rootY)
731 name = self.tk.call(args)
732 if not name: return None
733 return self._nametowidget(name)
734 def winfo_depth(self):
735 """Return the number of bits per pixel."""
736 return getint(self.tk.call('winfo', 'depth', self._w))
737 def winfo_exists(self):
738 """Return true if this widget exists."""
739 return getint(
740 self.tk.call('winfo', 'exists', self._w))
741 def winfo_fpixels(self, number):
742 """Return the number of pixels for the given distance NUMBER
743 (e.g. "3c") as float."""
744 return getdouble(self.tk.call(
745 'winfo', 'fpixels', self._w, number))
746 def winfo_geometry(self):
747 """Return geometry string for this widget in the form "widthxheight+X+Y"."""
748 return self.tk.call('winfo', 'geometry', self._w)
749 def winfo_height(self):
750 """Return height of this widget."""
751 return getint(
752 self.tk.call('winfo', 'height', self._w))
753 def winfo_id(self):
754 """Return identifier ID for this widget."""
755 return self.tk.getint(
756 self.tk.call('winfo', 'id', self._w))
757 def winfo_interps(self, displayof=0):
758 """Return the name of all Tcl interpreters for this display."""
759 args = ('winfo', 'interps') + self._displayof(displayof)
760 return self.tk.splitlist(self.tk.call(args))
761 def winfo_ismapped(self):
762 """Return true if this widget is mapped."""
763 return getint(
764 self.tk.call('winfo', 'ismapped', self._w))
765 def winfo_manager(self):
766 """Return the window mananger name for this widget."""
767 return self.tk.call('winfo', 'manager', self._w)
768 def winfo_name(self):
769 """Return the name of this widget."""
770 return self.tk.call('winfo', 'name', self._w)
771 def winfo_parent(self):
772 """Return the name of the parent of this widget."""
773 return self.tk.call('winfo', 'parent', self._w)
774 def winfo_pathname(self, id, displayof=0):
775 """Return the pathname of the widget given by ID."""
776 args = ('winfo', 'pathname') \
777 + self._displayof(displayof) + (id,)
778 return self.tk.call(args)
779 def winfo_pixels(self, number):
780 """Rounded integer value of winfo_fpixels."""
781 return getint(
782 self.tk.call('winfo', 'pixels', self._w, number))
783 def winfo_pointerx(self):
784 """Return the x coordinate of the pointer on the root window."""
785 return getint(
786 self.tk.call('winfo', 'pointerx', self._w))
787 def winfo_pointerxy(self):
788 """Return a tuple of x and y coordinates of the pointer on the root window."""
789 return self._getints(
790 self.tk.call('winfo', 'pointerxy', self._w))
791 def winfo_pointery(self):
792 """Return the y coordinate of the pointer on the root window."""
793 return getint(
794 self.tk.call('winfo', 'pointery', self._w))
795 def winfo_reqheight(self):
796 """Return requested height of this widget."""
797 return getint(
798 self.tk.call('winfo', 'reqheight', self._w))
799 def winfo_reqwidth(self):
800 """Return requested width of this widget."""
801 return getint(
802 self.tk.call('winfo', 'reqwidth', self._w))
803 def winfo_rgb(self, color):
804 """Return tuple of decimal values for red, green, blue for
805 COLOR in this widget."""
806 return self._getints(
807 self.tk.call('winfo', 'rgb', self._w, color))
808 def winfo_rootx(self):
809 """Return x coordinate of upper left corner of this widget on the
810 root window."""
811 return getint(
812 self.tk.call('winfo', 'rootx', self._w))
813 def winfo_rooty(self):
814 """Return y coordinate of upper left corner of this widget on the
815 root window."""
816 return getint(
817 self.tk.call('winfo', 'rooty', self._w))
818 def winfo_screen(self):
819 """Return the screen name of this widget."""
820 return self.tk.call('winfo', 'screen', self._w)
821 def winfo_screencells(self):
822 """Return the number of the cells in the colormap of the screen
823 of this widget."""
824 return getint(
825 self.tk.call('winfo', 'screencells', self._w))
826 def winfo_screendepth(self):
827 """Return the number of bits per pixel of the root window of the
828 screen of this widget."""
829 return getint(
830 self.tk.call('winfo', 'screendepth', self._w))
831 def winfo_screenheight(self):
832 """Return the number of pixels of the height of the screen of this widget
833 in pixel."""
834 return getint(
835 self.tk.call('winfo', 'screenheight', self._w))
836 def winfo_screenmmheight(self):
837 """Return the number of pixels of the height of the screen of
838 this widget in mm."""
839 return getint(
840 self.tk.call('winfo', 'screenmmheight', self._w))
841 def winfo_screenmmwidth(self):
842 """Return the number of pixels of the width of the screen of
843 this widget in mm."""
844 return getint(
845 self.tk.call('winfo', 'screenmmwidth', self._w))
846 def winfo_screenvisual(self):
847 """Return one of the strings directcolor, grayscale, pseudocolor,
848 staticcolor, staticgray, or truecolor for the default
849 colormodel of this screen."""
850 return self.tk.call('winfo', 'screenvisual', self._w)
851 def winfo_screenwidth(self):
852 """Return the number of pixels of the width of the screen of
853 this widget in pixel."""
854 return getint(
855 self.tk.call('winfo', 'screenwidth', self._w))
856 def winfo_server(self):
857 """Return information of the X-Server of the screen of this widget in
858 the form "XmajorRminor vendor vendorVersion"."""
859 return self.tk.call('winfo', 'server', self._w)
860 def winfo_toplevel(self):
861 """Return the toplevel widget of this widget."""
862 return self._nametowidget(self.tk.call(
863 'winfo', 'toplevel', self._w))
864 def winfo_viewable(self):
865 """Return true if the widget and all its higher ancestors are mapped."""
866 return getint(
867 self.tk.call('winfo', 'viewable', self._w))
868 def winfo_visual(self):
869 """Return one of the strings directcolor, grayscale, pseudocolor,
870 staticcolor, staticgray, or truecolor for the
871 colormodel of this widget."""
872 return self.tk.call('winfo', 'visual', self._w)
873 def winfo_visualid(self):
874 """Return the X identifier for the visual for this widget."""
875 return self.tk.call('winfo', 'visualid', self._w)
876 def winfo_visualsavailable(self, includeids=0):
877 """Return a list of all visuals available for the screen
878 of this widget.
Guido van Rossum5917ecb2000-06-29 16:30:50 +0000879
Fredrik Lundh06d28152000-08-09 18:03:12 +0000880 Each item in the list consists of a visual name (see winfo_visual), a
881 depth and if INCLUDEIDS=1 is given also the X identifier."""
882 data = self.tk.split(
883 self.tk.call('winfo', 'visualsavailable', self._w,
884 includeids and 'includeids' or None))
Guido van Rossum13257902007-06-07 23:15:56 +0000885 if isinstance(data, str):
Fredrik Lundh24037f72000-08-09 19:26:47 +0000886 data = [self.tk.split(data)]
Alexander Belopolsky022f0492010-11-22 19:40:51 +0000887 return [self.__winfo_parseitem(x) for x in data]
Fredrik Lundh06d28152000-08-09 18:03:12 +0000888 def __winfo_parseitem(self, t):
889 """Internal function."""
890 return t[:1] + tuple(map(self.__winfo_getint, t[1:]))
891 def __winfo_getint(self, x):
892 """Internal function."""
Eric S. Raymondfc170b12001-02-09 11:51:27 +0000893 return int(x, 0)
Fredrik Lundh06d28152000-08-09 18:03:12 +0000894 def winfo_vrootheight(self):
895 """Return the height of the virtual root window associated with this
896 widget in pixels. If there is no virtual root window return the
897 height of the screen."""
898 return getint(
899 self.tk.call('winfo', 'vrootheight', self._w))
900 def winfo_vrootwidth(self):
901 """Return the width of the virtual root window associated with this
902 widget in pixel. If there is no virtual root window return the
903 width of the screen."""
904 return getint(
905 self.tk.call('winfo', 'vrootwidth', self._w))
906 def winfo_vrootx(self):
907 """Return the x offset of the virtual root relative to the root
908 window of the screen of this widget."""
909 return getint(
910 self.tk.call('winfo', 'vrootx', self._w))
911 def winfo_vrooty(self):
912 """Return the y offset of the virtual root relative to the root
913 window of the screen of this widget."""
914 return getint(
915 self.tk.call('winfo', 'vrooty', self._w))
916 def winfo_width(self):
917 """Return the width of this widget."""
918 return getint(
919 self.tk.call('winfo', 'width', self._w))
920 def winfo_x(self):
921 """Return the x coordinate of the upper left corner of this widget
922 in the parent."""
923 return getint(
924 self.tk.call('winfo', 'x', self._w))
925 def winfo_y(self):
926 """Return the y coordinate of the upper left corner of this widget
927 in the parent."""
928 return getint(
929 self.tk.call('winfo', 'y', self._w))
930 def update(self):
931 """Enter event loop until all pending events have been processed by Tcl."""
932 self.tk.call('update')
933 def update_idletasks(self):
934 """Enter event loop until all idle callbacks have been called. This
935 will update the display of windows but not process events caused by
936 the user."""
937 self.tk.call('update', 'idletasks')
938 def bindtags(self, tagList=None):
939 """Set or get the list of bindtags for this widget.
Guido van Rossum5917ecb2000-06-29 16:30:50 +0000940
Fredrik Lundh06d28152000-08-09 18:03:12 +0000941 With no argument return the list of all bindtags associated with
942 this widget. With a list of strings as argument the bindtags are
943 set to this list. The bindtags determine in which order events are
944 processed (see bind)."""
945 if tagList is None:
946 return self.tk.splitlist(
947 self.tk.call('bindtags', self._w))
948 else:
949 self.tk.call('bindtags', self._w, tagList)
950 def _bind(self, what, sequence, func, add, needcleanup=1):
951 """Internal function."""
Guido van Rossum13257902007-06-07 23:15:56 +0000952 if isinstance(func, str):
Fredrik Lundh06d28152000-08-09 18:03:12 +0000953 self.tk.call(what + (sequence, func))
954 elif func:
955 funcid = self._register(func, self._substitute,
956 needcleanup)
957 cmd = ('%sif {"[%s %s]" == "break"} break\n'
958 %
959 (add and '+' or '',
Martin v. Löwisc8718c12001-08-09 16:57:33 +0000960 funcid, self._subst_format_str))
Fredrik Lundh06d28152000-08-09 18:03:12 +0000961 self.tk.call(what + (sequence, cmd))
962 return funcid
963 elif sequence:
964 return self.tk.call(what + (sequence,))
965 else:
966 return self.tk.splitlist(self.tk.call(what))
967 def bind(self, sequence=None, func=None, add=None):
968 """Bind to this widget at event SEQUENCE a call to function FUNC.
Guido van Rossum5917ecb2000-06-29 16:30:50 +0000969
Fredrik Lundh06d28152000-08-09 18:03:12 +0000970 SEQUENCE is a string of concatenated event
971 patterns. An event pattern is of the form
972 <MODIFIER-MODIFIER-TYPE-DETAIL> where MODIFIER is one
973 of Control, Mod2, M2, Shift, Mod3, M3, Lock, Mod4, M4,
974 Button1, B1, Mod5, M5 Button2, B2, Meta, M, Button3,
975 B3, Alt, Button4, B4, Double, Button5, B5 Triple,
976 Mod1, M1. TYPE is one of Activate, Enter, Map,
977 ButtonPress, Button, Expose, Motion, ButtonRelease
978 FocusIn, MouseWheel, Circulate, FocusOut, Property,
979 Colormap, Gravity Reparent, Configure, KeyPress, Key,
980 Unmap, Deactivate, KeyRelease Visibility, Destroy,
981 Leave and DETAIL is the button number for ButtonPress,
982 ButtonRelease and DETAIL is the Keysym for KeyPress and
983 KeyRelease. Examples are
984 <Control-Button-1> for pressing Control and mouse button 1 or
985 <Alt-A> for pressing A and the Alt key (KeyPress can be omitted).
986 An event pattern can also be a virtual event of the form
987 <<AString>> where AString can be arbitrary. This
988 event can be generated by event_generate.
989 If events are concatenated they must appear shortly
990 after each other.
Guido van Rossum5917ecb2000-06-29 16:30:50 +0000991
Fredrik Lundh06d28152000-08-09 18:03:12 +0000992 FUNC will be called if the event sequence occurs with an
993 instance of Event as argument. If the return value of FUNC is
994 "break" no further bound function is invoked.
Guido van Rossum5917ecb2000-06-29 16:30:50 +0000995
Fredrik Lundh06d28152000-08-09 18:03:12 +0000996 An additional boolean parameter ADD specifies whether FUNC will
997 be called additionally to the other bound function or whether
998 it will replace the previous function.
Guido van Rossum5917ecb2000-06-29 16:30:50 +0000999
Fredrik Lundh06d28152000-08-09 18:03:12 +00001000 Bind will return an identifier to allow deletion of the bound function with
1001 unbind without memory leak.
Guido van Rossum5917ecb2000-06-29 16:30:50 +00001002
Fredrik Lundh06d28152000-08-09 18:03:12 +00001003 If FUNC or SEQUENCE is omitted the bound function or list
1004 of bound events are returned."""
Guido van Rossum5917ecb2000-06-29 16:30:50 +00001005
Fredrik Lundh06d28152000-08-09 18:03:12 +00001006 return self._bind(('bind', self._w), sequence, func, add)
1007 def unbind(self, sequence, funcid=None):
1008 """Unbind for this widget for event SEQUENCE the
1009 function identified with FUNCID."""
1010 self.tk.call('bind', self._w, sequence, '')
1011 if funcid:
1012 self.deletecommand(funcid)
1013 def bind_all(self, sequence=None, func=None, add=None):
1014 """Bind to all widgets at an event SEQUENCE a call to function FUNC.
1015 An additional boolean parameter ADD specifies whether FUNC will
1016 be called additionally to the other bound function or whether
1017 it will replace the previous function. See bind for the return value."""
1018 return self._bind(('bind', 'all'), sequence, func, add, 0)
1019 def unbind_all(self, sequence):
1020 """Unbind for all widgets for event SEQUENCE all functions."""
1021 self.tk.call('bind', 'all' , sequence, '')
1022 def bind_class(self, className, sequence=None, func=None, add=None):
Guido van Rossum5917ecb2000-06-29 16:30:50 +00001023
Fredrik Lundh06d28152000-08-09 18:03:12 +00001024 """Bind to widgets with bindtag CLASSNAME at event
1025 SEQUENCE a call of function FUNC. An additional
1026 boolean parameter ADD specifies whether FUNC will be
1027 called additionally to the other bound function or
1028 whether it will replace the previous function. See bind for
1029 the return value."""
Guido van Rossum5917ecb2000-06-29 16:30:50 +00001030
Fredrik Lundh06d28152000-08-09 18:03:12 +00001031 return self._bind(('bind', className), sequence, func, add, 0)
1032 def unbind_class(self, className, sequence):
1033 """Unbind for a all widgets with bindtag CLASSNAME for event SEQUENCE
1034 all functions."""
1035 self.tk.call('bind', className , sequence, '')
1036 def mainloop(self, n=0):
1037 """Call the mainloop of Tk."""
1038 self.tk.mainloop(n)
1039 def quit(self):
1040 """Quit the Tcl interpreter. All widgets will be destroyed."""
1041 self.tk.quit()
1042 def _getints(self, string):
1043 """Internal function."""
1044 if string:
1045 return tuple(map(getint, self.tk.splitlist(string)))
1046 def _getdoubles(self, string):
1047 """Internal function."""
1048 if string:
1049 return tuple(map(getdouble, self.tk.splitlist(string)))
1050 def _getboolean(self, string):
1051 """Internal function."""
1052 if string:
1053 return self.tk.getboolean(string)
1054 def _displayof(self, displayof):
1055 """Internal function."""
1056 if displayof:
1057 return ('-displayof', displayof)
1058 if displayof is None:
1059 return ('-displayof', self._w)
1060 return ()
Ned Deily4d377d92012-05-15 18:08:11 -07001061 @property
1062 def _windowingsystem(self):
1063 """Internal function."""
1064 try:
1065 return self._root()._windowingsystem_cached
1066 except AttributeError:
1067 ws = self._root()._windowingsystem_cached = \
1068 self.tk.call('tk', 'windowingsystem')
1069 return ws
Fredrik Lundh06d28152000-08-09 18:03:12 +00001070 def _options(self, cnf, kw = None):
1071 """Internal function."""
1072 if kw:
1073 cnf = _cnfmerge((cnf, kw))
1074 else:
1075 cnf = _cnfmerge(cnf)
1076 res = ()
1077 for k, v in cnf.items():
1078 if v is not None:
1079 if k[-1] == '_': k = k[:-1]
Florent Xicluna5d1155c2011-10-28 14:45:05 +02001080 if callable(v):
Fredrik Lundh06d28152000-08-09 18:03:12 +00001081 v = self._register(v)
Georg Brandlbf1eb632008-05-29 07:19:00 +00001082 elif isinstance(v, (tuple, list)):
Georg Brandl3b550032008-06-03 10:25:47 +00001083 nv = []
Georg Brandlbf1eb632008-05-29 07:19:00 +00001084 for item in v:
Georg Brandl3b550032008-06-03 10:25:47 +00001085 if isinstance(item, int):
1086 nv.append(str(item))
1087 elif isinstance(item, str):
1088 nv.append(('{%s}' if ' ' in item else '%s') % item)
1089 else:
Georg Brandlbf1eb632008-05-29 07:19:00 +00001090 break
1091 else:
Georg Brandl3b550032008-06-03 10:25:47 +00001092 v = ' '.join(nv)
Fredrik Lundh06d28152000-08-09 18:03:12 +00001093 res = res + ('-'+k, v)
1094 return res
1095 def nametowidget(self, name):
1096 """Return the Tkinter instance of a widget identified by
1097 its Tcl name NAME."""
Martin v. Löwiscdfae162008-08-02 07:23:15 +00001098 name = str(name).split('.')
Fredrik Lundh06d28152000-08-09 18:03:12 +00001099 w = self
Martin v. Löwiscdfae162008-08-02 07:23:15 +00001100
1101 if not name[0]:
Fredrik Lundh06d28152000-08-09 18:03:12 +00001102 w = w._root()
1103 name = name[1:]
Martin v. Löwiscdfae162008-08-02 07:23:15 +00001104
1105 for n in name:
1106 if not n:
1107 break
1108 w = w.children[n]
1109
Fredrik Lundh06d28152000-08-09 18:03:12 +00001110 return w
1111 _nametowidget = nametowidget
1112 def _register(self, func, subst=None, needcleanup=1):
1113 """Return a newly created Tcl function. If this
1114 function is called, the Python function FUNC will
1115 be executed. An optional function SUBST can
1116 be given which will be executed before FUNC."""
1117 f = CallWrapper(func, subst, self).__call__
Walter Dörwald70a6b492004-02-12 17:35:32 +00001118 name = repr(id(f))
Fredrik Lundh06d28152000-08-09 18:03:12 +00001119 try:
Christian Heimesff737952007-11-27 10:40:20 +00001120 func = func.__func__
Fredrik Lundh06d28152000-08-09 18:03:12 +00001121 except AttributeError:
1122 pass
1123 try:
1124 name = name + func.__name__
1125 except AttributeError:
1126 pass
1127 self.tk.createcommand(name, f)
1128 if needcleanup:
1129 if self._tclCommands is None:
1130 self._tclCommands = []
1131 self._tclCommands.append(name)
Fredrik Lundh06d28152000-08-09 18:03:12 +00001132 return name
1133 register = _register
1134 def _root(self):
1135 """Internal function."""
1136 w = self
1137 while w.master: w = w.master
1138 return w
1139 _subst_format = ('%#', '%b', '%f', '%h', '%k',
1140 '%s', '%t', '%w', '%x', '%y',
1141 '%A', '%E', '%K', '%N', '%W', '%T', '%X', '%Y', '%D')
Martin v. Löwisc8718c12001-08-09 16:57:33 +00001142 _subst_format_str = " ".join(_subst_format)
Fredrik Lundh06d28152000-08-09 18:03:12 +00001143 def _substitute(self, *args):
1144 """Internal function."""
1145 if len(args) != len(self._subst_format): return args
1146 getboolean = self.tk.getboolean
Martin v. Löwis043bbc72003-03-29 09:47:21 +00001147
Fredrik Lundh06d28152000-08-09 18:03:12 +00001148 getint = int
Martin v. Löwis043bbc72003-03-29 09:47:21 +00001149 def getint_event(s):
1150 """Tk changed behavior in 8.4.2, returning "??" rather more often."""
1151 try:
1152 return int(s)
1153 except ValueError:
1154 return s
1155
Fredrik Lundh06d28152000-08-09 18:03:12 +00001156 nsign, b, f, h, k, s, t, w, x, y, A, E, K, N, W, T, X, Y, D = args
1157 # Missing: (a, c, d, m, o, v, B, R)
1158 e = Event()
Martin v. Löwis043bbc72003-03-29 09:47:21 +00001159 # serial field: valid vor all events
1160 # number of button: ButtonPress and ButtonRelease events only
1161 # height field: Configure, ConfigureRequest, Create,
1162 # ResizeRequest, and Expose events only
1163 # keycode field: KeyPress and KeyRelease events only
1164 # time field: "valid for events that contain a time field"
1165 # width field: Configure, ConfigureRequest, Create, ResizeRequest,
1166 # and Expose events only
1167 # x field: "valid for events that contain a x field"
1168 # y field: "valid for events that contain a y field"
1169 # keysym as decimal: KeyPress and KeyRelease events only
1170 # x_root, y_root fields: ButtonPress, ButtonRelease, KeyPress,
1171 # KeyRelease,and Motion events
Fredrik Lundh06d28152000-08-09 18:03:12 +00001172 e.serial = getint(nsign)
Martin v. Löwis043bbc72003-03-29 09:47:21 +00001173 e.num = getint_event(b)
Fredrik Lundh06d28152000-08-09 18:03:12 +00001174 try: e.focus = getboolean(f)
1175 except TclError: pass
Martin v. Löwis043bbc72003-03-29 09:47:21 +00001176 e.height = getint_event(h)
1177 e.keycode = getint_event(k)
1178 e.state = getint_event(s)
1179 e.time = getint_event(t)
1180 e.width = getint_event(w)
1181 e.x = getint_event(x)
1182 e.y = getint_event(y)
Fredrik Lundh06d28152000-08-09 18:03:12 +00001183 e.char = A
1184 try: e.send_event = getboolean(E)
1185 except TclError: pass
1186 e.keysym = K
Martin v. Löwis043bbc72003-03-29 09:47:21 +00001187 e.keysym_num = getint_event(N)
Fredrik Lundh06d28152000-08-09 18:03:12 +00001188 e.type = T
1189 try:
1190 e.widget = self._nametowidget(W)
1191 except KeyError:
1192 e.widget = W
Martin v. Löwis043bbc72003-03-29 09:47:21 +00001193 e.x_root = getint_event(X)
1194 e.y_root = getint_event(Y)
Fredrik Lundha249f162000-09-07 15:05:09 +00001195 try:
1196 e.delta = getint(D)
1197 except ValueError:
1198 e.delta = 0
Fredrik Lundh06d28152000-08-09 18:03:12 +00001199 return (e,)
1200 def _report_exception(self):
1201 """Internal function."""
Neal Norwitzac3625f2006-03-17 05:49:33 +00001202 exc, val, tb = sys.exc_info()
Fredrik Lundh06d28152000-08-09 18:03:12 +00001203 root = self._root()
1204 root.report_callback_exception(exc, val, tb)
Martin v. Löwis6ce13152002-10-10 14:36:13 +00001205 def _configure(self, cmd, cnf, kw):
1206 """Internal function."""
1207 if kw:
1208 cnf = _cnfmerge((cnf, kw))
1209 elif cnf:
1210 cnf = _cnfmerge(cnf)
1211 if cnf is None:
1212 cnf = {}
1213 for x in self.tk.split(
1214 self.tk.call(_flatten((self._w, cmd)))):
1215 cnf[x[0][1:]] = (x[0][1:],) + x[1:]
1216 return cnf
Guido van Rossum13257902007-06-07 23:15:56 +00001217 if isinstance(cnf, str):
Martin v. Löwis6ce13152002-10-10 14:36:13 +00001218 x = self.tk.split(
1219 self.tk.call(_flatten((self._w, cmd, '-'+cnf))))
1220 return (x[0][1:],) + x[1:]
1221 self.tk.call(_flatten((self._w, cmd)) + self._options(cnf))
Fredrik Lundh06d28152000-08-09 18:03:12 +00001222 # These used to be defined in Widget:
1223 def configure(self, cnf=None, **kw):
1224 """Configure resources of a widget.
Barry Warsaw107e6231998-12-15 00:44:15 +00001225
Fredrik Lundh06d28152000-08-09 18:03:12 +00001226 The values for resources are specified as keyword
1227 arguments. To get an overview about
1228 the allowed keyword arguments call the method keys.
1229 """
Martin v. Löwis6ce13152002-10-10 14:36:13 +00001230 return self._configure('configure', cnf, kw)
Fredrik Lundh06d28152000-08-09 18:03:12 +00001231 config = configure
1232 def cget(self, key):
1233 """Return the resource value for a KEY given as string."""
1234 return self.tk.call(self._w, 'cget', '-' + key)
1235 __getitem__ = cget
1236 def __setitem__(self, key, value):
1237 self.configure({key: value})
1238 def keys(self):
1239 """Return a list of all resource names of this widget."""
Alexander Belopolsky022f0492010-11-22 19:40:51 +00001240 return [x[0][1:] for x in
1241 self.tk.split(self.tk.call(self._w, 'configure'))]
Fredrik Lundh06d28152000-08-09 18:03:12 +00001242 def __str__(self):
1243 """Return the window path name of this widget."""
1244 return self._w
1245 # Pack methods that apply to the master
1246 _noarg_ = ['_noarg_']
1247 def pack_propagate(self, flag=_noarg_):
1248 """Set or get the status for propagation of geometry information.
Guido van Rossum5917ecb2000-06-29 16:30:50 +00001249
Fredrik Lundh06d28152000-08-09 18:03:12 +00001250 A boolean argument specifies whether the geometry information
1251 of the slaves will determine the size of this widget. If no argument
1252 is given the current setting will be returned.
1253 """
1254 if flag is Misc._noarg_:
1255 return self._getboolean(self.tk.call(
1256 'pack', 'propagate', self._w))
1257 else:
1258 self.tk.call('pack', 'propagate', self._w, flag)
1259 propagate = pack_propagate
1260 def pack_slaves(self):
1261 """Return a list of all slaves of this widget
1262 in its packing order."""
Alexander Belopolsky022f0492010-11-22 19:40:51 +00001263 return [self._nametowidget(x) for x in
1264 self.tk.splitlist(
1265 self.tk.call('pack', 'slaves', self._w))]
Fredrik Lundh06d28152000-08-09 18:03:12 +00001266 slaves = pack_slaves
1267 # Place method that applies to the master
1268 def place_slaves(self):
1269 """Return a list of all slaves of this widget
1270 in its packing order."""
Alexander Belopolsky022f0492010-11-22 19:40:51 +00001271 return [self._nametowidget(x) for x in
1272 self.tk.splitlist(
Fredrik Lundh06d28152000-08-09 18:03:12 +00001273 self.tk.call(
Alexander Belopolsky022f0492010-11-22 19:40:51 +00001274 'place', 'slaves', self._w))]
Fredrik Lundh06d28152000-08-09 18:03:12 +00001275 # Grid methods that apply to the master
Martin v. Löwis5c3c4242012-03-13 13:40:42 -07001276 def grid_anchor(self, anchor=None): # new in Tk 8.5
1277 """The anchor value controls how to place the grid within the
1278 master when no row/column has any weight.
1279
1280 The default anchor is nw."""
1281 self.tk.call('grid', 'anchor', self._w, anchor)
1282 anchor = grid_anchor
Fredrik Lundh06d28152000-08-09 18:03:12 +00001283 def grid_bbox(self, column=None, row=None, col2=None, row2=None):
1284 """Return a tuple of integer coordinates for the bounding
1285 box of this widget controlled by the geometry manager grid.
Guido van Rossum5917ecb2000-06-29 16:30:50 +00001286
Fredrik Lundh06d28152000-08-09 18:03:12 +00001287 If COLUMN, ROW is given the bounding box applies from
1288 the cell with row and column 0 to the specified
1289 cell. If COL2 and ROW2 are given the bounding box
1290 starts at that cell.
Guido van Rossum5917ecb2000-06-29 16:30:50 +00001291
Fredrik Lundh06d28152000-08-09 18:03:12 +00001292 The returned integers specify the offset of the upper left
1293 corner in the master widget and the width and height.
1294 """
1295 args = ('grid', 'bbox', self._w)
1296 if column is not None and row is not None:
1297 args = args + (column, row)
1298 if col2 is not None and row2 is not None:
1299 args = args + (col2, row2)
Raymond Hettingerff41c482003-04-06 09:01:11 +00001300 return self._getints(self.tk.call(*args)) or None
Fredrik Lundh06d28152000-08-09 18:03:12 +00001301 bbox = grid_bbox
1302 def _grid_configure(self, command, index, cnf, kw):
1303 """Internal function."""
Guido van Rossum13257902007-06-07 23:15:56 +00001304 if isinstance(cnf, str) and not kw:
Fredrik Lundh06d28152000-08-09 18:03:12 +00001305 if cnf[-1:] == '_':
1306 cnf = cnf[:-1]
1307 if cnf[:1] != '-':
1308 cnf = '-'+cnf
1309 options = (cnf,)
1310 else:
1311 options = self._options(cnf, kw)
1312 if not options:
1313 res = self.tk.call('grid',
1314 command, self._w, index)
1315 words = self.tk.splitlist(res)
1316 dict = {}
1317 for i in range(0, len(words), 2):
1318 key = words[i][1:]
1319 value = words[i+1]
1320 if not value:
1321 value = None
1322 elif '.' in value:
1323 value = getdouble(value)
1324 else:
1325 value = getint(value)
1326 dict[key] = value
1327 return dict
1328 res = self.tk.call(
1329 ('grid', command, self._w, index)
1330 + options)
1331 if len(options) == 1:
1332 if not res: return None
1333 # In Tk 7.5, -width can be a float
1334 if '.' in res: return getdouble(res)
1335 return getint(res)
1336 def grid_columnconfigure(self, index, cnf={}, **kw):
1337 """Configure column INDEX of a grid.
Guido van Rossum80f8be81997-12-02 19:51:39 +00001338
Fredrik Lundh06d28152000-08-09 18:03:12 +00001339 Valid resources are minsize (minimum size of the column),
1340 weight (how much does additional space propagate to this column)
1341 and pad (how much space to let additionally)."""
1342 return self._grid_configure('columnconfigure', index, cnf, kw)
1343 columnconfigure = grid_columnconfigure
Martin v. Löwisdc579092001-10-13 09:33:51 +00001344 def grid_location(self, x, y):
1345 """Return a tuple of column and row which identify the cell
1346 at which the pixel at position X and Y inside the master
1347 widget is located."""
1348 return self._getints(
1349 self.tk.call(
1350 'grid', 'location', self._w, x, y)) or None
Fredrik Lundh06d28152000-08-09 18:03:12 +00001351 def grid_propagate(self, flag=_noarg_):
1352 """Set or get the status for propagation of geometry information.
Guido van Rossum80f8be81997-12-02 19:51:39 +00001353
Fredrik Lundh06d28152000-08-09 18:03:12 +00001354 A boolean argument specifies whether the geometry information
1355 of the slaves will determine the size of this widget. If no argument
1356 is given, the current setting will be returned.
1357 """
1358 if flag is Misc._noarg_:
1359 return self._getboolean(self.tk.call(
1360 'grid', 'propagate', self._w))
1361 else:
1362 self.tk.call('grid', 'propagate', self._w, flag)
1363 def grid_rowconfigure(self, index, cnf={}, **kw):
1364 """Configure row INDEX of a grid.
Guido van Rossum80f8be81997-12-02 19:51:39 +00001365
Fredrik Lundh06d28152000-08-09 18:03:12 +00001366 Valid resources are minsize (minimum size of the row),
1367 weight (how much does additional space propagate to this row)
1368 and pad (how much space to let additionally)."""
1369 return self._grid_configure('rowconfigure', index, cnf, kw)
1370 rowconfigure = grid_rowconfigure
1371 def grid_size(self):
1372 """Return a tuple of the number of column and rows in the grid."""
1373 return self._getints(
1374 self.tk.call('grid', 'size', self._w)) or None
1375 size = grid_size
1376 def grid_slaves(self, row=None, column=None):
1377 """Return a list of all slaves of this widget
1378 in its packing order."""
1379 args = ()
1380 if row is not None:
1381 args = args + ('-row', row)
1382 if column is not None:
1383 args = args + ('-column', column)
Alexander Belopolsky022f0492010-11-22 19:40:51 +00001384 return [self._nametowidget(x) for x in
1385 self.tk.splitlist(self.tk.call(
1386 ('grid', 'slaves', self._w) + args))]
Guido van Rossum80f8be81997-12-02 19:51:39 +00001387
Fredrik Lundh06d28152000-08-09 18:03:12 +00001388 # Support for the "event" command, new in Tk 4.2.
1389 # By Case Roole.
Guido van Rossum80f8be81997-12-02 19:51:39 +00001390
Fredrik Lundh06d28152000-08-09 18:03:12 +00001391 def event_add(self, virtual, *sequences):
1392 """Bind a virtual event VIRTUAL (of the form <<Name>>)
1393 to an event SEQUENCE such that the virtual event is triggered
1394 whenever SEQUENCE occurs."""
1395 args = ('event', 'add', virtual) + sequences
1396 self.tk.call(args)
Guido van Rossumc2966511998-04-10 19:16:10 +00001397
Fredrik Lundh06d28152000-08-09 18:03:12 +00001398 def event_delete(self, virtual, *sequences):
1399 """Unbind a virtual event VIRTUAL from SEQUENCE."""
1400 args = ('event', 'delete', virtual) + sequences
1401 self.tk.call(args)
Guido van Rossumc2966511998-04-10 19:16:10 +00001402
Fredrik Lundh06d28152000-08-09 18:03:12 +00001403 def event_generate(self, sequence, **kw):
1404 """Generate an event SEQUENCE. Additional
1405 keyword arguments specify parameter of the event
1406 (e.g. x, y, rootx, rooty)."""
1407 args = ('event', 'generate', self._w, sequence)
1408 for k, v in kw.items():
1409 args = args + ('-%s' % k, str(v))
1410 self.tk.call(args)
1411
1412 def event_info(self, virtual=None):
1413 """Return a list of all virtual events or the information
1414 about the SEQUENCE bound to the virtual event VIRTUAL."""
1415 return self.tk.splitlist(
1416 self.tk.call('event', 'info', virtual))
1417
1418 # Image related commands
1419
1420 def image_names(self):
1421 """Return a list of all existing image names."""
1422 return self.tk.call('image', 'names')
1423
1424 def image_types(self):
1425 """Return a list of all available image types (e.g. phote bitmap)."""
1426 return self.tk.call('image', 'types')
Guido van Rossumc2966511998-04-10 19:16:10 +00001427
Guido van Rossum80f8be81997-12-02 19:51:39 +00001428
Guido van Rossuma5773dd1995-09-07 19:22:00 +00001429class CallWrapper:
Fredrik Lundh06d28152000-08-09 18:03:12 +00001430 """Internal class. Stores function to call when some user
1431 defined Tcl function is called e.g. after an event occurred."""
1432 def __init__(self, func, subst, widget):
1433 """Store FUNC, SUBST and WIDGET as members."""
1434 self.func = func
1435 self.subst = subst
1436 self.widget = widget
1437 def __call__(self, *args):
1438 """Apply first function SUBST to arguments, than FUNC."""
1439 try:
1440 if self.subst:
Raymond Hettingerff41c482003-04-06 09:01:11 +00001441 args = self.subst(*args)
1442 return self.func(*args)
Guido van Rossumb940e112007-01-10 16:19:56 +00001443 except SystemExit as msg:
Collin Winterce36ad82007-08-30 01:19:48 +00001444 raise SystemExit(msg)
Fredrik Lundh06d28152000-08-09 18:03:12 +00001445 except:
1446 self.widget._report_exception()
Guido van Rossum18468821994-06-20 07:49:28 +00001447
Guido van Rossume365a591998-05-01 19:48:20 +00001448
Guilherme Polo1fff0082009-08-14 15:05:30 +00001449class XView:
1450 """Mix-in class for querying and changing the horizontal position
1451 of a widget's window."""
1452
1453 def xview(self, *args):
1454 """Query and change the horizontal position of the view."""
1455 res = self.tk.call(self._w, 'xview', *args)
1456 if not args:
1457 return self._getdoubles(res)
1458
1459 def xview_moveto(self, fraction):
1460 """Adjusts the view in the window so that FRACTION of the
1461 total width of the canvas is off-screen to the left."""
1462 self.tk.call(self._w, 'xview', 'moveto', fraction)
1463
1464 def xview_scroll(self, number, what):
1465 """Shift the x-view according to NUMBER which is measured in "units"
1466 or "pages" (WHAT)."""
1467 self.tk.call(self._w, 'xview', 'scroll', number, what)
1468
1469
1470class YView:
1471 """Mix-in class for querying and changing the vertical position
1472 of a widget's window."""
1473
1474 def yview(self, *args):
1475 """Query and change the vertical position of the view."""
1476 res = self.tk.call(self._w, 'yview', *args)
1477 if not args:
1478 return self._getdoubles(res)
1479
1480 def yview_moveto(self, fraction):
1481 """Adjusts the view in the window so that FRACTION of the
1482 total height of the canvas is off-screen to the top."""
1483 self.tk.call(self._w, 'yview', 'moveto', fraction)
1484
1485 def yview_scroll(self, number, what):
1486 """Shift the y-view according to NUMBER which is measured in
1487 "units" or "pages" (WHAT)."""
1488 self.tk.call(self._w, 'yview', 'scroll', number, what)
1489
1490
Guido van Rossum18468821994-06-20 07:49:28 +00001491class Wm:
Fredrik Lundh06d28152000-08-09 18:03:12 +00001492 """Provides functions for the communication with the window manager."""
Raymond Hettingerff41c482003-04-06 09:01:11 +00001493
Fredrik Lundh06d28152000-08-09 18:03:12 +00001494 def wm_aspect(self,
1495 minNumer=None, minDenom=None,
1496 maxNumer=None, maxDenom=None):
1497 """Instruct the window manager to set the aspect ratio (width/height)
1498 of this widget to be between MINNUMER/MINDENOM and MAXNUMER/MAXDENOM. Return a tuple
1499 of the actual values if no argument is given."""
1500 return self._getints(
1501 self.tk.call('wm', 'aspect', self._w,
1502 minNumer, minDenom,
1503 maxNumer, maxDenom))
1504 aspect = wm_aspect
Raymond Hettingerff41c482003-04-06 09:01:11 +00001505
Martin v. Löwis2ec36272002-10-13 10:22:08 +00001506 def wm_attributes(self, *args):
1507 """This subcommand returns or sets platform specific attributes
Raymond Hettingerff41c482003-04-06 09:01:11 +00001508
1509 The first form returns a list of the platform specific flags and
1510 their values. The second form returns the value for the specific
Martin v. Löwis2ec36272002-10-13 10:22:08 +00001511 option. The third form sets one or more of the values. The values
1512 are as follows:
Raymond Hettingerff41c482003-04-06 09:01:11 +00001513
1514 On Windows, -disabled gets or sets whether the window is in a
Martin v. Löwis2ec36272002-10-13 10:22:08 +00001515 disabled state. -toolwindow gets or sets the style of the window
Raymond Hettingerff41c482003-04-06 09:01:11 +00001516 to toolwindow (as defined in the MSDN). -topmost gets or sets
1517 whether this is a topmost window (displays above all other
Martin v. Löwis2ec36272002-10-13 10:22:08 +00001518 windows).
Raymond Hettingerff41c482003-04-06 09:01:11 +00001519
1520 On Macintosh, XXXXX
1521
Martin v. Löwis2ec36272002-10-13 10:22:08 +00001522 On Unix, there are currently no special attribute values.
1523 """
1524 args = ('wm', 'attributes', self._w) + args
1525 return self.tk.call(args)
1526 attributes=wm_attributes
Raymond Hettingerff41c482003-04-06 09:01:11 +00001527
Fredrik Lundh06d28152000-08-09 18:03:12 +00001528 def wm_client(self, name=None):
1529 """Store NAME in WM_CLIENT_MACHINE property of this widget. Return
1530 current value."""
1531 return self.tk.call('wm', 'client', self._w, name)
1532 client = wm_client
1533 def wm_colormapwindows(self, *wlist):
1534 """Store list of window names (WLIST) into WM_COLORMAPWINDOWS property
1535 of this widget. This list contains windows whose colormaps differ from their
1536 parents. Return current list of widgets if WLIST is empty."""
1537 if len(wlist) > 1:
1538 wlist = (wlist,) # Tk needs a list of windows here
1539 args = ('wm', 'colormapwindows', self._w) + wlist
Alexander Belopolsky022f0492010-11-22 19:40:51 +00001540 return [self._nametowidget(x) for x in self.tk.call(args)]
Fredrik Lundh06d28152000-08-09 18:03:12 +00001541 colormapwindows = wm_colormapwindows
1542 def wm_command(self, value=None):
1543 """Store VALUE in WM_COMMAND property. It is the command
1544 which shall be used to invoke the application. Return current
1545 command if VALUE is None."""
1546 return self.tk.call('wm', 'command', self._w, value)
1547 command = wm_command
1548 def wm_deiconify(self):
1549 """Deiconify this widget. If it was never mapped it will not be mapped.
1550 On Windows it will raise this widget and give it the focus."""
1551 return self.tk.call('wm', 'deiconify', self._w)
1552 deiconify = wm_deiconify
1553 def wm_focusmodel(self, model=None):
1554 """Set focus model to MODEL. "active" means that this widget will claim
1555 the focus itself, "passive" means that the window manager shall give
1556 the focus. Return current focus model if MODEL is None."""
1557 return self.tk.call('wm', 'focusmodel', self._w, model)
1558 focusmodel = wm_focusmodel
Martin v. Löwis5c3c4242012-03-13 13:40:42 -07001559 def wm_forget(self, window): # new in Tk 8.5
1560 """The window will be unmappend from the screen and will no longer
1561 be managed by wm. toplevel windows will be treated like frame
1562 windows once they are no longer managed by wm, however, the menu
1563 option configuration will be remembered and the menus will return
1564 once the widget is managed again."""
1565 self.tk.call('wm', 'forget', window)
1566 forget = wm_forget
Fredrik Lundh06d28152000-08-09 18:03:12 +00001567 def wm_frame(self):
1568 """Return identifier for decorative frame of this widget if present."""
1569 return self.tk.call('wm', 'frame', self._w)
1570 frame = wm_frame
1571 def wm_geometry(self, newGeometry=None):
1572 """Set geometry to NEWGEOMETRY of the form =widthxheight+x+y. Return
1573 current value if None is given."""
1574 return self.tk.call('wm', 'geometry', self._w, newGeometry)
1575 geometry = wm_geometry
1576 def wm_grid(self,
1577 baseWidth=None, baseHeight=None,
1578 widthInc=None, heightInc=None):
1579 """Instruct the window manager that this widget shall only be
1580 resized on grid boundaries. WIDTHINC and HEIGHTINC are the width and
1581 height of a grid unit in pixels. BASEWIDTH and BASEHEIGHT are the
1582 number of grid units requested in Tk_GeometryRequest."""
1583 return self._getints(self.tk.call(
1584 'wm', 'grid', self._w,
1585 baseWidth, baseHeight, widthInc, heightInc))
1586 grid = wm_grid
1587 def wm_group(self, pathName=None):
1588 """Set the group leader widgets for related widgets to PATHNAME. Return
1589 the group leader of this widget if None is given."""
1590 return self.tk.call('wm', 'group', self._w, pathName)
1591 group = wm_group
Thomas Wouters0e3f5912006-08-11 14:57:12 +00001592 def wm_iconbitmap(self, bitmap=None, default=None):
Fredrik Lundh06d28152000-08-09 18:03:12 +00001593 """Set bitmap for the iconified widget to BITMAP. Return
Thomas Wouters0e3f5912006-08-11 14:57:12 +00001594 the bitmap if None is given.
1595
1596 Under Windows, the DEFAULT parameter can be used to set the icon
1597 for the widget and any descendents that don't have an icon set
1598 explicitly. DEFAULT can be the relative path to a .ico file
1599 (example: root.iconbitmap(default='myicon.ico') ). See Tk
1600 documentation for more information."""
1601 if default:
1602 return self.tk.call('wm', 'iconbitmap', self._w, '-default', default)
1603 else:
1604 return self.tk.call('wm', 'iconbitmap', self._w, bitmap)
Fredrik Lundh06d28152000-08-09 18:03:12 +00001605 iconbitmap = wm_iconbitmap
1606 def wm_iconify(self):
1607 """Display widget as icon."""
1608 return self.tk.call('wm', 'iconify', self._w)
1609 iconify = wm_iconify
1610 def wm_iconmask(self, bitmap=None):
1611 """Set mask for the icon bitmap of this widget. Return the
1612 mask if None is given."""
1613 return self.tk.call('wm', 'iconmask', self._w, bitmap)
1614 iconmask = wm_iconmask
1615 def wm_iconname(self, newName=None):
1616 """Set the name of the icon for this widget. Return the name if
1617 None is given."""
1618 return self.tk.call('wm', 'iconname', self._w, newName)
1619 iconname = wm_iconname
Martin v. Löwis5c3c4242012-03-13 13:40:42 -07001620 def wm_iconphoto(self, default=False, *args): # new in Tk 8.5
1621 """Sets the titlebar icon for this window based on the named photo
1622 images passed through args. If default is True, this is applied to
1623 all future created toplevels as well.
1624
1625 The data in the images is taken as a snapshot at the time of
1626 invocation. If the images are later changed, this is not reflected
1627 to the titlebar icons. Multiple images are accepted to allow
1628 different images sizes to be provided. The window manager may scale
1629 provided icons to an appropriate size.
1630
1631 On Windows, the images are packed into a Windows icon structure.
1632 This will override an icon specified to wm_iconbitmap, and vice
1633 versa.
1634
1635 On X, the images are arranged into the _NET_WM_ICON X property,
1636 which most modern window managers support. An icon specified by
1637 wm_iconbitmap may exist simuultaneously.
1638
1639 On Macintosh, this currently does nothing."""
1640 if default:
1641 self.tk.call('wm', 'iconphoto', self._w, "-default", *args)
1642 else:
1643 self.tk.call('wm', 'iconphoto', self._w, *args)
1644 iconphoto = wm_iconphoto
Fredrik Lundh06d28152000-08-09 18:03:12 +00001645 def wm_iconposition(self, x=None, y=None):
1646 """Set the position of the icon of this widget to X and Y. Return
1647 a tuple of the current values of X and X if None is given."""
1648 return self._getints(self.tk.call(
1649 'wm', 'iconposition', self._w, x, y))
1650 iconposition = wm_iconposition
1651 def wm_iconwindow(self, pathName=None):
1652 """Set widget PATHNAME to be displayed instead of icon. Return the current
1653 value if None is given."""
1654 return self.tk.call('wm', 'iconwindow', self._w, pathName)
1655 iconwindow = wm_iconwindow
Martin v. Löwis5c3c4242012-03-13 13:40:42 -07001656 def wm_manage(self, widget): # new in Tk 8.5
1657 """The widget specified will become a stand alone top-level window.
1658 The window will be decorated with the window managers title bar,
1659 etc."""
1660 self.tk.call('wm', 'manage', widget)
1661 manage = wm_manage
Fredrik Lundh06d28152000-08-09 18:03:12 +00001662 def wm_maxsize(self, width=None, height=None):
1663 """Set max WIDTH and HEIGHT for this widget. If the window is gridded
1664 the values are given in grid units. Return the current values if None
1665 is given."""
1666 return self._getints(self.tk.call(
1667 'wm', 'maxsize', self._w, width, height))
1668 maxsize = wm_maxsize
1669 def wm_minsize(self, width=None, height=None):
1670 """Set min WIDTH and HEIGHT for this widget. If the window is gridded
1671 the values are given in grid units. Return the current values if None
1672 is given."""
1673 return self._getints(self.tk.call(
1674 'wm', 'minsize', self._w, width, height))
1675 minsize = wm_minsize
1676 def wm_overrideredirect(self, boolean=None):
1677 """Instruct the window manager to ignore this widget
1678 if BOOLEAN is given with 1. Return the current value if None
1679 is given."""
1680 return self._getboolean(self.tk.call(
1681 'wm', 'overrideredirect', self._w, boolean))
1682 overrideredirect = wm_overrideredirect
1683 def wm_positionfrom(self, who=None):
1684 """Instruct the window manager that the position of this widget shall
1685 be defined by the user if WHO is "user", and by its own policy if WHO is
1686 "program"."""
1687 return self.tk.call('wm', 'positionfrom', self._w, who)
1688 positionfrom = wm_positionfrom
1689 def wm_protocol(self, name=None, func=None):
1690 """Bind function FUNC to command NAME for this widget.
1691 Return the function bound to NAME if None is given. NAME could be
1692 e.g. "WM_SAVE_YOURSELF" or "WM_DELETE_WINDOW"."""
Florent Xicluna5d1155c2011-10-28 14:45:05 +02001693 if callable(func):
Fredrik Lundh06d28152000-08-09 18:03:12 +00001694 command = self._register(func)
1695 else:
1696 command = func
1697 return self.tk.call(
1698 'wm', 'protocol', self._w, name, command)
1699 protocol = wm_protocol
1700 def wm_resizable(self, width=None, height=None):
1701 """Instruct the window manager whether this width can be resized
1702 in WIDTH or HEIGHT. Both values are boolean values."""
1703 return self.tk.call('wm', 'resizable', self._w, width, height)
1704 resizable = wm_resizable
1705 def wm_sizefrom(self, who=None):
1706 """Instruct the window manager that the size of this widget shall
1707 be defined by the user if WHO is "user", and by its own policy if WHO is
1708 "program"."""
1709 return self.tk.call('wm', 'sizefrom', self._w, who)
1710 sizefrom = wm_sizefrom
Fredrik Lundh289ad8f2000-08-09 19:11:59 +00001711 def wm_state(self, newstate=None):
1712 """Query or set the state of this widget as one of normal, icon,
1713 iconic (see wm_iconwindow), withdrawn, or zoomed (Windows only)."""
1714 return self.tk.call('wm', 'state', self._w, newstate)
Fredrik Lundh06d28152000-08-09 18:03:12 +00001715 state = wm_state
1716 def wm_title(self, string=None):
1717 """Set the title of this widget."""
1718 return self.tk.call('wm', 'title', self._w, string)
1719 title = wm_title
1720 def wm_transient(self, master=None):
1721 """Instruct the window manager that this widget is transient
1722 with regard to widget MASTER."""
1723 return self.tk.call('wm', 'transient', self._w, master)
1724 transient = wm_transient
1725 def wm_withdraw(self):
1726 """Withdraw this widget from the screen such that it is unmapped
1727 and forgotten by the window manager. Re-draw it with wm_deiconify."""
1728 return self.tk.call('wm', 'withdraw', self._w)
1729 withdraw = wm_withdraw
Guido van Rossume365a591998-05-01 19:48:20 +00001730
Guido van Rossum18468821994-06-20 07:49:28 +00001731
1732class Tk(Misc, Wm):
Fredrik Lundh06d28152000-08-09 18:03:12 +00001733 """Toplevel widget of Tk which represents mostly the main window
Ezio Melotti42da6632011-03-15 05:18:48 +02001734 of an application. It has an associated Tcl interpreter."""
Fredrik Lundh06d28152000-08-09 18:03:12 +00001735 _w = '.'
Martin v. Löwis9441c072004-08-03 18:36:25 +00001736 def __init__(self, screenName=None, baseName=None, className='Tk',
1737 useTk=1, sync=0, use=None):
Fredrik Lundh06d28152000-08-09 18:03:12 +00001738 """Return a new Toplevel widget on screen SCREENNAME. A new Tcl interpreter will
1739 be created. BASENAME will be used for the identification of the profile file (see
1740 readprofile).
1741 It is constructed from sys.argv[0] without extensions if None is given. CLASSNAME
1742 is the name of the widget class."""
Fredrik Lundh06d28152000-08-09 18:03:12 +00001743 self.master = None
1744 self.children = {}
David Aschere2b4b322004-02-18 05:59:53 +00001745 self._tkloaded = 0
1746 # to avoid recursions in the getattr code in case of failure, we
1747 # ensure that self.tk is always _something_.
Tim Peters182b5ac2004-07-18 06:16:08 +00001748 self.tk = None
Fredrik Lundh06d28152000-08-09 18:03:12 +00001749 if baseName is None:
Florent Xicluna54540ec2011-11-04 08:29:17 +01001750 import os
Fredrik Lundh06d28152000-08-09 18:03:12 +00001751 baseName = os.path.basename(sys.argv[0])
1752 baseName, ext = os.path.splitext(baseName)
1753 if ext not in ('.py', '.pyc', '.pyo'):
1754 baseName = baseName + ext
David Aschere2b4b322004-02-18 05:59:53 +00001755 interactive = 0
Martin v. Löwis9441c072004-08-03 18:36:25 +00001756 self.tk = _tkinter.create(screenName, baseName, className, interactive, wantobjects, useTk, sync, use)
David Aschere2b4b322004-02-18 05:59:53 +00001757 if useTk:
1758 self._loadtk()
1759 self.readprofile(baseName, className)
1760 def loadtk(self):
1761 if not self._tkloaded:
1762 self.tk.loadtk()
1763 self._loadtk()
1764 def _loadtk(self):
1765 self._tkloaded = 1
1766 global _default_root
Fredrik Lundh06d28152000-08-09 18:03:12 +00001767 # Version sanity checks
1768 tk_version = self.tk.getvar('tk_version')
1769 if tk_version != _tkinter.TK_VERSION:
Collin Winterce36ad82007-08-30 01:19:48 +00001770 raise RuntimeError("tk.h version (%s) doesn't match libtk.a version (%s)"
1771 % (_tkinter.TK_VERSION, tk_version))
Martin v. Löwis54895972003-05-24 11:37:15 +00001772 # Under unknown circumstances, tcl_version gets coerced to float
1773 tcl_version = str(self.tk.getvar('tcl_version'))
Fredrik Lundh06d28152000-08-09 18:03:12 +00001774 if tcl_version != _tkinter.TCL_VERSION:
Collin Winterce36ad82007-08-30 01:19:48 +00001775 raise RuntimeError("tcl.h version (%s) doesn't match libtcl.a version (%s)" \
1776 % (_tkinter.TCL_VERSION, tcl_version))
Fredrik Lundh06d28152000-08-09 18:03:12 +00001777 if TkVersion < 4.0:
Collin Winterce36ad82007-08-30 01:19:48 +00001778 raise RuntimeError("Tk 4.0 or higher is required; found Tk %s"
1779 % str(TkVersion))
Martin v. Löwis4afe1542005-03-01 08:09:28 +00001780 # Create and register the tkerror and exit commands
1781 # We need to inline parts of _register here, _ register
1782 # would register differently-named commands.
1783 if self._tclCommands is None:
1784 self._tclCommands = []
Fredrik Lundh06d28152000-08-09 18:03:12 +00001785 self.tk.createcommand('tkerror', _tkerror)
1786 self.tk.createcommand('exit', _exit)
Martin v. Löwis4afe1542005-03-01 08:09:28 +00001787 self._tclCommands.append('tkerror')
1788 self._tclCommands.append('exit')
Fredrik Lundh06d28152000-08-09 18:03:12 +00001789 if _support_default_root and not _default_root:
1790 _default_root = self
1791 self.protocol("WM_DELETE_WINDOW", self.destroy)
1792 def destroy(self):
1793 """Destroy this and all descendants widgets. This will
1794 end the application of this Tcl interpreter."""
Guido van Rossumb5a755e2007-07-18 18:15:48 +00001795 for c in list(self.children.values()): c.destroy()
Fredrik Lundh06d28152000-08-09 18:03:12 +00001796 self.tk.call('destroy', self._w)
1797 Misc.destroy(self)
1798 global _default_root
1799 if _support_default_root and _default_root is self:
1800 _default_root = None
1801 def readprofile(self, baseName, className):
1802 """Internal function. It reads BASENAME.tcl and CLASSNAME.tcl into
Neal Norwitz01688022007-08-12 00:43:29 +00001803 the Tcl Interpreter and calls exec on the contents of BASENAME.py and
1804 CLASSNAME.py if such a file exists in the home directory."""
Fredrik Lundh06d28152000-08-09 18:03:12 +00001805 import os
Guido van Rossume014a132006-08-19 16:53:45 +00001806 if 'HOME' in os.environ: home = os.environ['HOME']
Fredrik Lundh06d28152000-08-09 18:03:12 +00001807 else: home = os.curdir
1808 class_tcl = os.path.join(home, '.%s.tcl' % className)
1809 class_py = os.path.join(home, '.%s.py' % className)
1810 base_tcl = os.path.join(home, '.%s.tcl' % baseName)
1811 base_py = os.path.join(home, '.%s.py' % baseName)
1812 dir = {'self': self}
Georg Brandl14fc4272008-05-17 18:39:55 +00001813 exec('from tkinter import *', dir)
Fredrik Lundh06d28152000-08-09 18:03:12 +00001814 if os.path.isfile(class_tcl):
Fredrik Lundh06d28152000-08-09 18:03:12 +00001815 self.tk.call('source', class_tcl)
1816 if os.path.isfile(class_py):
Neal Norwitz01688022007-08-12 00:43:29 +00001817 exec(open(class_py).read(), dir)
Fredrik Lundh06d28152000-08-09 18:03:12 +00001818 if os.path.isfile(base_tcl):
Fredrik Lundh06d28152000-08-09 18:03:12 +00001819 self.tk.call('source', base_tcl)
1820 if os.path.isfile(base_py):
Neal Norwitz01688022007-08-12 00:43:29 +00001821 exec(open(base_py).read(), dir)
Fredrik Lundh06d28152000-08-09 18:03:12 +00001822 def report_callback_exception(self, exc, val, tb):
1823 """Internal function. It reports exception on sys.stderr."""
Florent Xicluna54540ec2011-11-04 08:29:17 +01001824 import traceback
Fredrik Lundh06d28152000-08-09 18:03:12 +00001825 sys.stderr.write("Exception in Tkinter callback\n")
1826 sys.last_type = exc
1827 sys.last_value = val
1828 sys.last_traceback = tb
1829 traceback.print_exception(exc, val, tb)
David Aschere2b4b322004-02-18 05:59:53 +00001830 def __getattr__(self, attr):
1831 "Delegate attribute access to the interpreter object"
1832 return getattr(self.tk, attr)
Guido van Rossum18468821994-06-20 07:49:28 +00001833
Guido van Rossum368e06b1997-11-07 20:38:49 +00001834# Ideally, the classes Pack, Place and Grid disappear, the
1835# pack/place/grid methods are defined on the Widget class, and
1836# everybody uses w.pack_whatever(...) instead of Pack.whatever(w,
1837# ...), with pack(), place() and grid() being short for
1838# pack_configure(), place_configure() and grid_columnconfigure(), and
1839# forget() being short for pack_forget(). As a practical matter, I'm
1840# afraid that there is too much code out there that may be using the
1841# Pack, Place or Grid class, so I leave them intact -- but only as
1842# backwards compatibility features. Also note that those methods that
1843# take a master as argument (e.g. pack_propagate) have been moved to
1844# the Misc class (which now incorporates all methods common between
1845# toplevel and interior widgets). Again, for compatibility, these are
1846# copied into the Pack, Place or Grid class.
1847
David Aschere2b4b322004-02-18 05:59:53 +00001848
1849def Tcl(screenName=None, baseName=None, className='Tk', useTk=0):
1850 return Tk(screenName, baseName, className, useTk)
1851
Guido van Rossum18468821994-06-20 07:49:28 +00001852class Pack:
Fredrik Lundh06d28152000-08-09 18:03:12 +00001853 """Geometry manager Pack.
Guido van Rossum5917ecb2000-06-29 16:30:50 +00001854
Fredrik Lundh06d28152000-08-09 18:03:12 +00001855 Base class to use the methods pack_* in every widget."""
1856 def pack_configure(self, cnf={}, **kw):
1857 """Pack a widget in the parent widget. Use as options:
1858 after=widget - pack it after you have packed widget
1859 anchor=NSEW (or subset) - position widget according to
1860 given direction
Georg Brandlbf1eb632008-05-29 07:19:00 +00001861 before=widget - pack it before you will pack widget
Martin v. Löwisbfe175c2003-04-16 19:42:51 +00001862 expand=bool - expand widget if parent size grows
Fredrik Lundh06d28152000-08-09 18:03:12 +00001863 fill=NONE or X or Y or BOTH - fill widget if widget grows
1864 in=master - use master to contain this widget
Georg Brandlbf1eb632008-05-29 07:19:00 +00001865 in_=master - see 'in' option description
Fredrik Lundh06d28152000-08-09 18:03:12 +00001866 ipadx=amount - add internal padding in x direction
1867 ipady=amount - add internal padding in y direction
1868 padx=amount - add padding in x direction
1869 pady=amount - add padding in y direction
1870 side=TOP or BOTTOM or LEFT or RIGHT - where to add this widget.
1871 """
1872 self.tk.call(
1873 ('pack', 'configure', self._w)
1874 + self._options(cnf, kw))
1875 pack = configure = config = pack_configure
1876 def pack_forget(self):
1877 """Unmap this widget and do not use it for the packing order."""
1878 self.tk.call('pack', 'forget', self._w)
1879 forget = pack_forget
1880 def pack_info(self):
1881 """Return information about the packing options
1882 for this widget."""
1883 words = self.tk.splitlist(
1884 self.tk.call('pack', 'info', self._w))
1885 dict = {}
1886 for i in range(0, len(words), 2):
1887 key = words[i][1:]
1888 value = words[i+1]
1889 if value[:1] == '.':
1890 value = self._nametowidget(value)
1891 dict[key] = value
1892 return dict
1893 info = pack_info
1894 propagate = pack_propagate = Misc.pack_propagate
1895 slaves = pack_slaves = Misc.pack_slaves
Guido van Rossum18468821994-06-20 07:49:28 +00001896
1897class Place:
Fredrik Lundh06d28152000-08-09 18:03:12 +00001898 """Geometry manager Place.
Guido van Rossum5917ecb2000-06-29 16:30:50 +00001899
Fredrik Lundh06d28152000-08-09 18:03:12 +00001900 Base class to use the methods place_* in every widget."""
1901 def place_configure(self, cnf={}, **kw):
1902 """Place a widget in the parent widget. Use as options:
Georg Brandlbf1eb632008-05-29 07:19:00 +00001903 in=master - master relative to which the widget is placed
1904 in_=master - see 'in' option description
Fredrik Lundh06d28152000-08-09 18:03:12 +00001905 x=amount - locate anchor of this widget at position x of master
1906 y=amount - locate anchor of this widget at position y of master
1907 relx=amount - locate anchor of this widget between 0.0 and 1.0
1908 relative to width of master (1.0 is right edge)
Georg Brandlbf1eb632008-05-29 07:19:00 +00001909 rely=amount - locate anchor of this widget between 0.0 and 1.0
Fredrik Lundh06d28152000-08-09 18:03:12 +00001910 relative to height of master (1.0 is bottom edge)
Georg Brandlbf1eb632008-05-29 07:19:00 +00001911 anchor=NSEW (or subset) - position anchor according to given direction
Fredrik Lundh06d28152000-08-09 18:03:12 +00001912 width=amount - width of this widget in pixel
1913 height=amount - height of this widget in pixel
1914 relwidth=amount - width of this widget between 0.0 and 1.0
1915 relative to width of master (1.0 is the same width
Georg Brandlbf1eb632008-05-29 07:19:00 +00001916 as the master)
1917 relheight=amount - height of this widget between 0.0 and 1.0
Fredrik Lundh06d28152000-08-09 18:03:12 +00001918 relative to height of master (1.0 is the same
Georg Brandlbf1eb632008-05-29 07:19:00 +00001919 height as the master)
1920 bordermode="inside" or "outside" - whether to take border width of
1921 master widget into account
1922 """
Fredrik Lundh06d28152000-08-09 18:03:12 +00001923 self.tk.call(
1924 ('place', 'configure', self._w)
1925 + self._options(cnf, kw))
1926 place = configure = config = place_configure
1927 def place_forget(self):
1928 """Unmap this widget."""
1929 self.tk.call('place', 'forget', self._w)
1930 forget = place_forget
1931 def place_info(self):
1932 """Return information about the placing options
1933 for this widget."""
1934 words = self.tk.splitlist(
1935 self.tk.call('place', 'info', self._w))
1936 dict = {}
1937 for i in range(0, len(words), 2):
1938 key = words[i][1:]
1939 value = words[i+1]
1940 if value[:1] == '.':
1941 value = self._nametowidget(value)
1942 dict[key] = value
1943 return dict
1944 info = place_info
1945 slaves = place_slaves = Misc.place_slaves
Guido van Rossum18468821994-06-20 07:49:28 +00001946
Guido van Rossum37dcab11996-05-16 16:00:19 +00001947class Grid:
Fredrik Lundh06d28152000-08-09 18:03:12 +00001948 """Geometry manager Grid.
Guido van Rossum5917ecb2000-06-29 16:30:50 +00001949
Fredrik Lundh06d28152000-08-09 18:03:12 +00001950 Base class to use the methods grid_* in every widget."""
1951 # Thanks to Masazumi Yoshikawa (yosikawa@isi.edu)
1952 def grid_configure(self, cnf={}, **kw):
1953 """Position a widget in the parent widget in a grid. Use as options:
1954 column=number - use cell identified with given column (starting with 0)
1955 columnspan=number - this widget will span several columns
1956 in=master - use master to contain this widget
Georg Brandlbf1eb632008-05-29 07:19:00 +00001957 in_=master - see 'in' option description
Fredrik Lundh06d28152000-08-09 18:03:12 +00001958 ipadx=amount - add internal padding in x direction
1959 ipady=amount - add internal padding in y direction
1960 padx=amount - add padding in x direction
1961 pady=amount - add padding in y direction
1962 row=number - use cell identified with given row (starting with 0)
1963 rowspan=number - this widget will span several rows
1964 sticky=NSEW - if cell is larger on which sides will this
1965 widget stick to the cell boundary
1966 """
1967 self.tk.call(
1968 ('grid', 'configure', self._w)
1969 + self._options(cnf, kw))
1970 grid = configure = config = grid_configure
1971 bbox = grid_bbox = Misc.grid_bbox
1972 columnconfigure = grid_columnconfigure = Misc.grid_columnconfigure
1973 def grid_forget(self):
1974 """Unmap this widget."""
1975 self.tk.call('grid', 'forget', self._w)
1976 forget = grid_forget
1977 def grid_remove(self):
1978 """Unmap this widget but remember the grid options."""
1979 self.tk.call('grid', 'remove', self._w)
1980 def grid_info(self):
1981 """Return information about the options
1982 for positioning this widget in a grid."""
1983 words = self.tk.splitlist(
1984 self.tk.call('grid', 'info', self._w))
1985 dict = {}
1986 for i in range(0, len(words), 2):
1987 key = words[i][1:]
1988 value = words[i+1]
1989 if value[:1] == '.':
1990 value = self._nametowidget(value)
1991 dict[key] = value
1992 return dict
1993 info = grid_info
Martin v. Löwisdc579092001-10-13 09:33:51 +00001994 location = grid_location = Misc.grid_location
Fredrik Lundh06d28152000-08-09 18:03:12 +00001995 propagate = grid_propagate = Misc.grid_propagate
1996 rowconfigure = grid_rowconfigure = Misc.grid_rowconfigure
1997 size = grid_size = Misc.grid_size
1998 slaves = grid_slaves = Misc.grid_slaves
Guido van Rossum37dcab11996-05-16 16:00:19 +00001999
Guido van Rossum368e06b1997-11-07 20:38:49 +00002000class BaseWidget(Misc):
Fredrik Lundh06d28152000-08-09 18:03:12 +00002001 """Internal class."""
2002 def _setup(self, master, cnf):
2003 """Internal function. Sets up information about children."""
2004 if _support_default_root:
2005 global _default_root
2006 if not master:
2007 if not _default_root:
2008 _default_root = Tk()
2009 master = _default_root
2010 self.master = master
2011 self.tk = master.tk
2012 name = None
Guido van Rossume014a132006-08-19 16:53:45 +00002013 if 'name' in cnf:
Fredrik Lundh06d28152000-08-09 18:03:12 +00002014 name = cnf['name']
2015 del cnf['name']
2016 if not name:
Walter Dörwald70a6b492004-02-12 17:35:32 +00002017 name = repr(id(self))
Fredrik Lundh06d28152000-08-09 18:03:12 +00002018 self._name = name
2019 if master._w=='.':
2020 self._w = '.' + name
2021 else:
2022 self._w = master._w + '.' + name
2023 self.children = {}
Guido van Rossume014a132006-08-19 16:53:45 +00002024 if self._name in self.master.children:
Fredrik Lundh06d28152000-08-09 18:03:12 +00002025 self.master.children[self._name].destroy()
2026 self.master.children[self._name] = self
2027 def __init__(self, master, widgetName, cnf={}, kw={}, extra=()):
2028 """Construct a widget with the parent widget MASTER, a name WIDGETNAME
2029 and appropriate options."""
2030 if kw:
2031 cnf = _cnfmerge((cnf, kw))
2032 self.widgetName = widgetName
2033 BaseWidget._setup(self, master, cnf)
Hirokazu Yamamotoa18424c2008-11-04 06:26:27 +00002034 if self._tclCommands is None:
2035 self._tclCommands = []
Guilherme Polob212b752008-09-04 11:21:31 +00002036 classes = [(k, v) for k, v in cnf.items() if isinstance(k, type)]
2037 for k, v in classes:
2038 del cnf[k]
Fredrik Lundh06d28152000-08-09 18:03:12 +00002039 self.tk.call(
2040 (widgetName, self._w) + extra + self._options(cnf))
2041 for k, v in classes:
2042 k.configure(self, v)
2043 def destroy(self):
2044 """Destroy this and all descendants widgets."""
Guido van Rossum992d4a32007-07-11 13:09:30 +00002045 for c in list(self.children.values()): c.destroy()
Thomas Wouters0e3f5912006-08-11 14:57:12 +00002046 self.tk.call('destroy', self._w)
Guido van Rossume014a132006-08-19 16:53:45 +00002047 if self._name in self.master.children:
Fredrik Lundh06d28152000-08-09 18:03:12 +00002048 del self.master.children[self._name]
Fredrik Lundh06d28152000-08-09 18:03:12 +00002049 Misc.destroy(self)
2050 def _do(self, name, args=()):
2051 # XXX Obsolete -- better use self.tk.call directly!
2052 return self.tk.call((self._w, name) + args)
Guido van Rossum18468821994-06-20 07:49:28 +00002053
Guido van Rossum368e06b1997-11-07 20:38:49 +00002054class Widget(BaseWidget, Pack, Place, Grid):
Fredrik Lundh06d28152000-08-09 18:03:12 +00002055 """Internal class.
Guido van Rossum5917ecb2000-06-29 16:30:50 +00002056
Fredrik Lundh06d28152000-08-09 18:03:12 +00002057 Base class for a widget which can be positioned with the geometry managers
2058 Pack, Place or Grid."""
2059 pass
Guido van Rossum368e06b1997-11-07 20:38:49 +00002060
2061class Toplevel(BaseWidget, Wm):
Fredrik Lundh06d28152000-08-09 18:03:12 +00002062 """Toplevel widget, e.g. for dialogs."""
2063 def __init__(self, master=None, cnf={}, **kw):
2064 """Construct a toplevel widget with the parent MASTER.
Guido van Rossum5917ecb2000-06-29 16:30:50 +00002065
Fredrik Lundh06d28152000-08-09 18:03:12 +00002066 Valid resource names: background, bd, bg, borderwidth, class,
2067 colormap, container, cursor, height, highlightbackground,
2068 highlightcolor, highlightthickness, menu, relief, screen, takefocus,
2069 use, visual, width."""
2070 if kw:
2071 cnf = _cnfmerge((cnf, kw))
2072 extra = ()
2073 for wmkey in ['screen', 'class_', 'class', 'visual',
2074 'colormap']:
Guido van Rossume014a132006-08-19 16:53:45 +00002075 if wmkey in cnf:
Fredrik Lundh06d28152000-08-09 18:03:12 +00002076 val = cnf[wmkey]
2077 # TBD: a hack needed because some keys
2078 # are not valid as keyword arguments
2079 if wmkey[-1] == '_': opt = '-'+wmkey[:-1]
2080 else: opt = '-'+wmkey
2081 extra = extra + (opt, val)
2082 del cnf[wmkey]
2083 BaseWidget.__init__(self, master, 'toplevel', cnf, {}, extra)
2084 root = self._root()
2085 self.iconname(root.iconname())
2086 self.title(root.title())
2087 self.protocol("WM_DELETE_WINDOW", self.destroy)
Guido van Rossum18468821994-06-20 07:49:28 +00002088
2089class Button(Widget):
Fredrik Lundh06d28152000-08-09 18:03:12 +00002090 """Button widget."""
2091 def __init__(self, master=None, cnf={}, **kw):
2092 """Construct a button widget with the parent MASTER.
Raymond Hettingerff41c482003-04-06 09:01:11 +00002093
Martin v. Löwis2ec36272002-10-13 10:22:08 +00002094 STANDARD OPTIONS
Raymond Hettingerff41c482003-04-06 09:01:11 +00002095
Martin v. Löwis2ec36272002-10-13 10:22:08 +00002096 activebackground, activeforeground, anchor,
2097 background, bitmap, borderwidth, cursor,
Raymond Hettingerff41c482003-04-06 09:01:11 +00002098 disabledforeground, font, foreground
Martin v. Löwis2ec36272002-10-13 10:22:08 +00002099 highlightbackground, highlightcolor,
Raymond Hettingerff41c482003-04-06 09:01:11 +00002100 highlightthickness, image, justify,
Martin v. Löwis2ec36272002-10-13 10:22:08 +00002101 padx, pady, relief, repeatdelay,
Raymond Hettingerff41c482003-04-06 09:01:11 +00002102 repeatinterval, takefocus, text,
Martin v. Löwis2ec36272002-10-13 10:22:08 +00002103 textvariable, underline, wraplength
Raymond Hettingerff41c482003-04-06 09:01:11 +00002104
Martin v. Löwis2ec36272002-10-13 10:22:08 +00002105 WIDGET-SPECIFIC OPTIONS
Raymond Hettingerff41c482003-04-06 09:01:11 +00002106
Martin v. Löwis2ec36272002-10-13 10:22:08 +00002107 command, compound, default, height,
2108 overrelief, state, width
2109 """
Fredrik Lundh06d28152000-08-09 18:03:12 +00002110 Widget.__init__(self, master, 'button', cnf, kw)
Raymond Hettingerff41c482003-04-06 09:01:11 +00002111
Fredrik Lundh06d28152000-08-09 18:03:12 +00002112 def tkButtonEnter(self, *dummy):
2113 self.tk.call('tkButtonEnter', self._w)
Raymond Hettingerff41c482003-04-06 09:01:11 +00002114
Fredrik Lundh06d28152000-08-09 18:03:12 +00002115 def tkButtonLeave(self, *dummy):
2116 self.tk.call('tkButtonLeave', self._w)
Raymond Hettingerff41c482003-04-06 09:01:11 +00002117
Fredrik Lundh06d28152000-08-09 18:03:12 +00002118 def tkButtonDown(self, *dummy):
2119 self.tk.call('tkButtonDown', self._w)
Raymond Hettingerff41c482003-04-06 09:01:11 +00002120
Fredrik Lundh06d28152000-08-09 18:03:12 +00002121 def tkButtonUp(self, *dummy):
2122 self.tk.call('tkButtonUp', self._w)
Raymond Hettingerff41c482003-04-06 09:01:11 +00002123
Fredrik Lundh06d28152000-08-09 18:03:12 +00002124 def tkButtonInvoke(self, *dummy):
2125 self.tk.call('tkButtonInvoke', self._w)
Raymond Hettingerff41c482003-04-06 09:01:11 +00002126
Fredrik Lundh06d28152000-08-09 18:03:12 +00002127 def flash(self):
Raymond Hettingerff41c482003-04-06 09:01:11 +00002128 """Flash the button.
2129
2130 This is accomplished by redisplaying
2131 the button several times, alternating between active and
2132 normal colors. At the end of the flash the button is left
2133 in the same normal/active state as when the command was
2134 invoked. This command is ignored if the button's state is
Martin v. Löwis2ec36272002-10-13 10:22:08 +00002135 disabled.
2136 """
Fredrik Lundh06d28152000-08-09 18:03:12 +00002137 self.tk.call(self._w, 'flash')
Raymond Hettingerff41c482003-04-06 09:01:11 +00002138
Fredrik Lundh06d28152000-08-09 18:03:12 +00002139 def invoke(self):
Raymond Hettingerff41c482003-04-06 09:01:11 +00002140 """Invoke the command associated with the button.
2141
2142 The return value is the return value from the command,
Martin v. Löwis2ec36272002-10-13 10:22:08 +00002143 or an empty string if there is no command associated with
2144 the button. This command is ignored if the button's state
2145 is disabled.
2146 """
Fredrik Lundh06d28152000-08-09 18:03:12 +00002147 return self.tk.call(self._w, 'invoke')
Guido van Rossum18468821994-06-20 07:49:28 +00002148
Guilherme Polo1fff0082009-08-14 15:05:30 +00002149class Canvas(Widget, XView, YView):
Fredrik Lundh06d28152000-08-09 18:03:12 +00002150 """Canvas widget to display graphical elements like lines or text."""
2151 def __init__(self, master=None, cnf={}, **kw):
2152 """Construct a canvas widget with the parent MASTER.
Guido van Rossum5917ecb2000-06-29 16:30:50 +00002153
Fredrik Lundh06d28152000-08-09 18:03:12 +00002154 Valid resource names: background, bd, bg, borderwidth, closeenough,
2155 confine, cursor, height, highlightbackground, highlightcolor,
2156 highlightthickness, insertbackground, insertborderwidth,
2157 insertofftime, insertontime, insertwidth, offset, relief,
2158 scrollregion, selectbackground, selectborderwidth, selectforeground,
2159 state, takefocus, width, xscrollcommand, xscrollincrement,
2160 yscrollcommand, yscrollincrement."""
2161 Widget.__init__(self, master, 'canvas', cnf, kw)
2162 def addtag(self, *args):
2163 """Internal function."""
2164 self.tk.call((self._w, 'addtag') + args)
2165 def addtag_above(self, newtag, tagOrId):
2166 """Add tag NEWTAG to all items above TAGORID."""
2167 self.addtag(newtag, 'above', tagOrId)
2168 def addtag_all(self, newtag):
2169 """Add tag NEWTAG to all items."""
2170 self.addtag(newtag, 'all')
2171 def addtag_below(self, newtag, tagOrId):
2172 """Add tag NEWTAG to all items below TAGORID."""
2173 self.addtag(newtag, 'below', tagOrId)
2174 def addtag_closest(self, newtag, x, y, halo=None, start=None):
2175 """Add tag NEWTAG to item which is closest to pixel at X, Y.
2176 If several match take the top-most.
2177 All items closer than HALO are considered overlapping (all are
2178 closests). If START is specified the next below this tag is taken."""
2179 self.addtag(newtag, 'closest', x, y, halo, start)
2180 def addtag_enclosed(self, newtag, x1, y1, x2, y2):
2181 """Add tag NEWTAG to all items in the rectangle defined
2182 by X1,Y1,X2,Y2."""
2183 self.addtag(newtag, 'enclosed', x1, y1, x2, y2)
2184 def addtag_overlapping(self, newtag, x1, y1, x2, y2):
2185 """Add tag NEWTAG to all items which overlap the rectangle
2186 defined by X1,Y1,X2,Y2."""
2187 self.addtag(newtag, 'overlapping', x1, y1, x2, y2)
2188 def addtag_withtag(self, newtag, tagOrId):
2189 """Add tag NEWTAG to all items with TAGORID."""
2190 self.addtag(newtag, 'withtag', tagOrId)
2191 def bbox(self, *args):
2192 """Return a tuple of X1,Y1,X2,Y2 coordinates for a rectangle
2193 which encloses all items with tags specified as arguments."""
2194 return self._getints(
2195 self.tk.call((self._w, 'bbox') + args)) or None
2196 def tag_unbind(self, tagOrId, sequence, funcid=None):
2197 """Unbind for all items with TAGORID for event SEQUENCE the
2198 function identified with FUNCID."""
2199 self.tk.call(self._w, 'bind', tagOrId, sequence, '')
2200 if funcid:
2201 self.deletecommand(funcid)
2202 def tag_bind(self, tagOrId, sequence=None, func=None, add=None):
2203 """Bind to all items with TAGORID at event SEQUENCE a call to function FUNC.
Guido van Rossum5917ecb2000-06-29 16:30:50 +00002204
Fredrik Lundh06d28152000-08-09 18:03:12 +00002205 An additional boolean parameter ADD specifies whether FUNC will be
2206 called additionally to the other bound function or whether it will
2207 replace the previous function. See bind for the return value."""
2208 return self._bind((self._w, 'bind', tagOrId),
2209 sequence, func, add)
2210 def canvasx(self, screenx, gridspacing=None):
2211 """Return the canvas x coordinate of pixel position SCREENX rounded
2212 to nearest multiple of GRIDSPACING units."""
2213 return getdouble(self.tk.call(
2214 self._w, 'canvasx', screenx, gridspacing))
2215 def canvasy(self, screeny, gridspacing=None):
2216 """Return the canvas y coordinate of pixel position SCREENY rounded
2217 to nearest multiple of GRIDSPACING units."""
2218 return getdouble(self.tk.call(
2219 self._w, 'canvasy', screeny, gridspacing))
2220 def coords(self, *args):
2221 """Return a list of coordinates for the item given in ARGS."""
2222 # XXX Should use _flatten on args
Alexander Belopolsky022f0492010-11-22 19:40:51 +00002223 return [getdouble(x) for x in
Guido van Rossum0bd54331998-05-19 21:18:13 +00002224 self.tk.splitlist(
Alexander Belopolsky022f0492010-11-22 19:40:51 +00002225 self.tk.call((self._w, 'coords') + args))]
Fredrik Lundh06d28152000-08-09 18:03:12 +00002226 def _create(self, itemType, args, kw): # Args: (val, val, ..., cnf={})
2227 """Internal function."""
2228 args = _flatten(args)
2229 cnf = args[-1]
Guido van Rossum13257902007-06-07 23:15:56 +00002230 if isinstance(cnf, (dict, tuple)):
Fredrik Lundh06d28152000-08-09 18:03:12 +00002231 args = args[:-1]
2232 else:
2233 cnf = {}
Raymond Hettingerff41c482003-04-06 09:01:11 +00002234 return getint(self.tk.call(
2235 self._w, 'create', itemType,
2236 *(args + self._options(cnf, kw))))
Fredrik Lundh06d28152000-08-09 18:03:12 +00002237 def create_arc(self, *args, **kw):
2238 """Create arc shaped region with coordinates x1,y1,x2,y2."""
2239 return self._create('arc', args, kw)
2240 def create_bitmap(self, *args, **kw):
2241 """Create bitmap with coordinates x1,y1."""
2242 return self._create('bitmap', args, kw)
2243 def create_image(self, *args, **kw):
2244 """Create image item with coordinates x1,y1."""
2245 return self._create('image', args, kw)
2246 def create_line(self, *args, **kw):
2247 """Create line with coordinates x1,y1,...,xn,yn."""
2248 return self._create('line', args, kw)
2249 def create_oval(self, *args, **kw):
2250 """Create oval with coordinates x1,y1,x2,y2."""
2251 return self._create('oval', args, kw)
2252 def create_polygon(self, *args, **kw):
2253 """Create polygon with coordinates x1,y1,...,xn,yn."""
2254 return self._create('polygon', args, kw)
2255 def create_rectangle(self, *args, **kw):
2256 """Create rectangle with coordinates x1,y1,x2,y2."""
2257 return self._create('rectangle', args, kw)
2258 def create_text(self, *args, **kw):
2259 """Create text with coordinates x1,y1."""
2260 return self._create('text', args, kw)
2261 def create_window(self, *args, **kw):
2262 """Create window with coordinates x1,y1,x2,y2."""
2263 return self._create('window', args, kw)
2264 def dchars(self, *args):
2265 """Delete characters of text items identified by tag or id in ARGS (possibly
2266 several times) from FIRST to LAST character (including)."""
2267 self.tk.call((self._w, 'dchars') + args)
2268 def delete(self, *args):
2269 """Delete items identified by all tag or ids contained in ARGS."""
2270 self.tk.call((self._w, 'delete') + args)
2271 def dtag(self, *args):
2272 """Delete tag or id given as last arguments in ARGS from items
2273 identified by first argument in ARGS."""
2274 self.tk.call((self._w, 'dtag') + args)
2275 def find(self, *args):
2276 """Internal function."""
2277 return self._getints(
2278 self.tk.call((self._w, 'find') + args)) or ()
2279 def find_above(self, tagOrId):
2280 """Return items above TAGORID."""
2281 return self.find('above', tagOrId)
2282 def find_all(self):
2283 """Return all items."""
2284 return self.find('all')
2285 def find_below(self, tagOrId):
2286 """Return all items below TAGORID."""
2287 return self.find('below', tagOrId)
2288 def find_closest(self, x, y, halo=None, start=None):
2289 """Return item which is closest to pixel at X, Y.
2290 If several match take the top-most.
2291 All items closer than HALO are considered overlapping (all are
2292 closests). If START is specified the next below this tag is taken."""
2293 return self.find('closest', x, y, halo, start)
2294 def find_enclosed(self, x1, y1, x2, y2):
2295 """Return all items in rectangle defined
2296 by X1,Y1,X2,Y2."""
2297 return self.find('enclosed', x1, y1, x2, y2)
2298 def find_overlapping(self, x1, y1, x2, y2):
2299 """Return all items which overlap the rectangle
2300 defined by X1,Y1,X2,Y2."""
2301 return self.find('overlapping', x1, y1, x2, y2)
2302 def find_withtag(self, tagOrId):
2303 """Return all items with TAGORID."""
2304 return self.find('withtag', tagOrId)
2305 def focus(self, *args):
2306 """Set focus to the first item specified in ARGS."""
2307 return self.tk.call((self._w, 'focus') + args)
2308 def gettags(self, *args):
2309 """Return tags associated with the first item specified in ARGS."""
2310 return self.tk.splitlist(
2311 self.tk.call((self._w, 'gettags') + args))
2312 def icursor(self, *args):
2313 """Set cursor at position POS in the item identified by TAGORID.
2314 In ARGS TAGORID must be first."""
2315 self.tk.call((self._w, 'icursor') + args)
2316 def index(self, *args):
2317 """Return position of cursor as integer in item specified in ARGS."""
2318 return getint(self.tk.call((self._w, 'index') + args))
2319 def insert(self, *args):
2320 """Insert TEXT in item TAGORID at position POS. ARGS must
2321 be TAGORID POS TEXT."""
2322 self.tk.call((self._w, 'insert') + args)
2323 def itemcget(self, tagOrId, option):
2324 """Return the resource value for an OPTION for item TAGORID."""
2325 return self.tk.call(
2326 (self._w, 'itemcget') + (tagOrId, '-'+option))
2327 def itemconfigure(self, tagOrId, cnf=None, **kw):
2328 """Configure resources of an item TAGORID.
Guido van Rossum5917ecb2000-06-29 16:30:50 +00002329
Fredrik Lundh06d28152000-08-09 18:03:12 +00002330 The values for resources are specified as keyword
2331 arguments. To get an overview about
2332 the allowed keyword arguments call the method without arguments.
2333 """
Martin v. Löwis6ce13152002-10-10 14:36:13 +00002334 return self._configure(('itemconfigure', tagOrId), cnf, kw)
Fredrik Lundh06d28152000-08-09 18:03:12 +00002335 itemconfig = itemconfigure
2336 # lower, tkraise/lift hide Misc.lower, Misc.tkraise/lift,
2337 # so the preferred name for them is tag_lower, tag_raise
2338 # (similar to tag_bind, and similar to the Text widget);
2339 # unfortunately can't delete the old ones yet (maybe in 1.6)
2340 def tag_lower(self, *args):
2341 """Lower an item TAGORID given in ARGS
2342 (optional below another item)."""
2343 self.tk.call((self._w, 'lower') + args)
2344 lower = tag_lower
2345 def move(self, *args):
2346 """Move an item TAGORID given in ARGS."""
2347 self.tk.call((self._w, 'move') + args)
2348 def postscript(self, cnf={}, **kw):
2349 """Print the contents of the canvas to a postscript
2350 file. Valid options: colormap, colormode, file, fontmap,
2351 height, pageanchor, pageheight, pagewidth, pagex, pagey,
2352 rotate, witdh, x, y."""
2353 return self.tk.call((self._w, 'postscript') +
2354 self._options(cnf, kw))
2355 def tag_raise(self, *args):
2356 """Raise an item TAGORID given in ARGS
2357 (optional above another item)."""
2358 self.tk.call((self._w, 'raise') + args)
2359 lift = tkraise = tag_raise
2360 def scale(self, *args):
2361 """Scale item TAGORID with XORIGIN, YORIGIN, XSCALE, YSCALE."""
2362 self.tk.call((self._w, 'scale') + args)
2363 def scan_mark(self, x, y):
2364 """Remember the current X, Y coordinates."""
2365 self.tk.call(self._w, 'scan', 'mark', x, y)
Neal Norwitze931ed52003-01-10 23:24:32 +00002366 def scan_dragto(self, x, y, gain=10):
2367 """Adjust the view of the canvas to GAIN times the
Fredrik Lundh06d28152000-08-09 18:03:12 +00002368 difference between X and Y and the coordinates given in
2369 scan_mark."""
Neal Norwitze931ed52003-01-10 23:24:32 +00002370 self.tk.call(self._w, 'scan', 'dragto', x, y, gain)
Fredrik Lundh06d28152000-08-09 18:03:12 +00002371 def select_adjust(self, tagOrId, index):
2372 """Adjust the end of the selection near the cursor of an item TAGORID to index."""
2373 self.tk.call(self._w, 'select', 'adjust', tagOrId, index)
2374 def select_clear(self):
2375 """Clear the selection if it is in this widget."""
2376 self.tk.call(self._w, 'select', 'clear')
2377 def select_from(self, tagOrId, index):
2378 """Set the fixed end of a selection in item TAGORID to INDEX."""
2379 self.tk.call(self._w, 'select', 'from', tagOrId, index)
2380 def select_item(self):
2381 """Return the item which has the selection."""
Neal Norwitz58b63bf2002-07-23 02:52:58 +00002382 return self.tk.call(self._w, 'select', 'item') or None
Fredrik Lundh06d28152000-08-09 18:03:12 +00002383 def select_to(self, tagOrId, index):
2384 """Set the variable end of a selection in item TAGORID to INDEX."""
2385 self.tk.call(self._w, 'select', 'to', tagOrId, index)
2386 def type(self, tagOrId):
2387 """Return the type of the item TAGORID."""
2388 return self.tk.call(self._w, 'type', tagOrId) or None
Guido van Rossum18468821994-06-20 07:49:28 +00002389
2390class Checkbutton(Widget):
Fredrik Lundh06d28152000-08-09 18:03:12 +00002391 """Checkbutton widget which is either in on- or off-state."""
2392 def __init__(self, master=None, cnf={}, **kw):
2393 """Construct a checkbutton widget with the parent MASTER.
Guido van Rossum5917ecb2000-06-29 16:30:50 +00002394
Fredrik Lundh06d28152000-08-09 18:03:12 +00002395 Valid resource names: activebackground, activeforeground, anchor,
2396 background, bd, bg, bitmap, borderwidth, command, cursor,
2397 disabledforeground, fg, font, foreground, height,
2398 highlightbackground, highlightcolor, highlightthickness, image,
2399 indicatoron, justify, offvalue, onvalue, padx, pady, relief,
2400 selectcolor, selectimage, state, takefocus, text, textvariable,
2401 underline, variable, width, wraplength."""
2402 Widget.__init__(self, master, 'checkbutton', cnf, kw)
2403 def deselect(self):
2404 """Put the button in off-state."""
2405 self.tk.call(self._w, 'deselect')
2406 def flash(self):
2407 """Flash the button."""
2408 self.tk.call(self._w, 'flash')
2409 def invoke(self):
2410 """Toggle the button and invoke a command if given as resource."""
2411 return self.tk.call(self._w, 'invoke')
2412 def select(self):
2413 """Put the button in on-state."""
2414 self.tk.call(self._w, 'select')
2415 def toggle(self):
2416 """Toggle the button."""
2417 self.tk.call(self._w, 'toggle')
Guido van Rossum18468821994-06-20 07:49:28 +00002418
Guilherme Polo1fff0082009-08-14 15:05:30 +00002419class Entry(Widget, XView):
Fredrik Lundh06d28152000-08-09 18:03:12 +00002420 """Entry widget which allows to display simple text."""
2421 def __init__(self, master=None, cnf={}, **kw):
2422 """Construct an entry widget with the parent MASTER.
Guido van Rossum5917ecb2000-06-29 16:30:50 +00002423
Fredrik Lundh06d28152000-08-09 18:03:12 +00002424 Valid resource names: background, bd, bg, borderwidth, cursor,
2425 exportselection, fg, font, foreground, highlightbackground,
2426 highlightcolor, highlightthickness, insertbackground,
2427 insertborderwidth, insertofftime, insertontime, insertwidth,
2428 invalidcommand, invcmd, justify, relief, selectbackground,
2429 selectborderwidth, selectforeground, show, state, takefocus,
2430 textvariable, validate, validatecommand, vcmd, width,
2431 xscrollcommand."""
2432 Widget.__init__(self, master, 'entry', cnf, kw)
2433 def delete(self, first, last=None):
2434 """Delete text from FIRST to LAST (not included)."""
2435 self.tk.call(self._w, 'delete', first, last)
2436 def get(self):
2437 """Return the text."""
2438 return self.tk.call(self._w, 'get')
2439 def icursor(self, index):
2440 """Insert cursor at INDEX."""
2441 self.tk.call(self._w, 'icursor', index)
2442 def index(self, index):
2443 """Return position of cursor."""
2444 return getint(self.tk.call(
2445 self._w, 'index', index))
2446 def insert(self, index, string):
2447 """Insert STRING at INDEX."""
2448 self.tk.call(self._w, 'insert', index, string)
2449 def scan_mark(self, x):
2450 """Remember the current X, Y coordinates."""
2451 self.tk.call(self._w, 'scan', 'mark', x)
2452 def scan_dragto(self, x):
2453 """Adjust the view of the canvas to 10 times the
2454 difference between X and Y and the coordinates given in
2455 scan_mark."""
2456 self.tk.call(self._w, 'scan', 'dragto', x)
2457 def selection_adjust(self, index):
2458 """Adjust the end of the selection near the cursor to INDEX."""
2459 self.tk.call(self._w, 'selection', 'adjust', index)
2460 select_adjust = selection_adjust
2461 def selection_clear(self):
2462 """Clear the selection if it is in this widget."""
2463 self.tk.call(self._w, 'selection', 'clear')
2464 select_clear = selection_clear
2465 def selection_from(self, index):
2466 """Set the fixed end of a selection to INDEX."""
2467 self.tk.call(self._w, 'selection', 'from', index)
2468 select_from = selection_from
2469 def selection_present(self):
Guilherme Polo1fff0082009-08-14 15:05:30 +00002470 """Return True if there are characters selected in the entry, False
2471 otherwise."""
Fredrik Lundh06d28152000-08-09 18:03:12 +00002472 return self.tk.getboolean(
2473 self.tk.call(self._w, 'selection', 'present'))
2474 select_present = selection_present
2475 def selection_range(self, start, end):
2476 """Set the selection from START to END (not included)."""
2477 self.tk.call(self._w, 'selection', 'range', start, end)
2478 select_range = selection_range
2479 def selection_to(self, index):
2480 """Set the variable end of a selection to INDEX."""
2481 self.tk.call(self._w, 'selection', 'to', index)
2482 select_to = selection_to
Guido van Rossum18468821994-06-20 07:49:28 +00002483
2484class Frame(Widget):
Fredrik Lundh06d28152000-08-09 18:03:12 +00002485 """Frame widget which may contain other widgets and can have a 3D border."""
2486 def __init__(self, master=None, cnf={}, **kw):
2487 """Construct a frame widget with the parent MASTER.
Guido van Rossum5917ecb2000-06-29 16:30:50 +00002488
Fredrik Lundh06d28152000-08-09 18:03:12 +00002489 Valid resource names: background, bd, bg, borderwidth, class,
2490 colormap, container, cursor, height, highlightbackground,
2491 highlightcolor, highlightthickness, relief, takefocus, visual, width."""
2492 cnf = _cnfmerge((cnf, kw))
2493 extra = ()
Guido van Rossume014a132006-08-19 16:53:45 +00002494 if 'class_' in cnf:
Fredrik Lundh06d28152000-08-09 18:03:12 +00002495 extra = ('-class', cnf['class_'])
2496 del cnf['class_']
Guido van Rossume014a132006-08-19 16:53:45 +00002497 elif 'class' in cnf:
Fredrik Lundh06d28152000-08-09 18:03:12 +00002498 extra = ('-class', cnf['class'])
2499 del cnf['class']
2500 Widget.__init__(self, master, 'frame', cnf, {}, extra)
Guido van Rossum18468821994-06-20 07:49:28 +00002501
2502class Label(Widget):
Fredrik Lundh06d28152000-08-09 18:03:12 +00002503 """Label widget which can display text and bitmaps."""
2504 def __init__(self, master=None, cnf={}, **kw):
2505 """Construct a label widget with the parent MASTER.
Raymond Hettingerff41c482003-04-06 09:01:11 +00002506
Martin v. Löwis2ec36272002-10-13 10:22:08 +00002507 STANDARD OPTIONS
Raymond Hettingerff41c482003-04-06 09:01:11 +00002508
2509 activebackground, activeforeground, anchor,
2510 background, bitmap, borderwidth, cursor,
Martin v. Löwis2ec36272002-10-13 10:22:08 +00002511 disabledforeground, font, foreground,
Raymond Hettingerff41c482003-04-06 09:01:11 +00002512 highlightbackground, highlightcolor,
2513 highlightthickness, image, justify,
2514 padx, pady, relief, takefocus, text,
Martin v. Löwis2ec36272002-10-13 10:22:08 +00002515 textvariable, underline, wraplength
Raymond Hettingerff41c482003-04-06 09:01:11 +00002516
Martin v. Löwis2ec36272002-10-13 10:22:08 +00002517 WIDGET-SPECIFIC OPTIONS
Raymond Hettingerff41c482003-04-06 09:01:11 +00002518
Martin v. Löwis2ec36272002-10-13 10:22:08 +00002519 height, state, width
Raymond Hettingerff41c482003-04-06 09:01:11 +00002520
Martin v. Löwis2ec36272002-10-13 10:22:08 +00002521 """
Fredrik Lundh06d28152000-08-09 18:03:12 +00002522 Widget.__init__(self, master, 'label', cnf, kw)
Guido van Rossum761c5ab1995-07-14 15:29:10 +00002523
Guilherme Polo1fff0082009-08-14 15:05:30 +00002524class Listbox(Widget, XView, YView):
Fredrik Lundh06d28152000-08-09 18:03:12 +00002525 """Listbox widget which can display a list of strings."""
2526 def __init__(self, master=None, cnf={}, **kw):
2527 """Construct a listbox widget with the parent MASTER.
Guido van Rossum5917ecb2000-06-29 16:30:50 +00002528
Fredrik Lundh06d28152000-08-09 18:03:12 +00002529 Valid resource names: background, bd, bg, borderwidth, cursor,
2530 exportselection, fg, font, foreground, height, highlightbackground,
2531 highlightcolor, highlightthickness, relief, selectbackground,
2532 selectborderwidth, selectforeground, selectmode, setgrid, takefocus,
2533 width, xscrollcommand, yscrollcommand, listvariable."""
2534 Widget.__init__(self, master, 'listbox', cnf, kw)
2535 def activate(self, index):
2536 """Activate item identified by INDEX."""
2537 self.tk.call(self._w, 'activate', index)
2538 def bbox(self, *args):
2539 """Return a tuple of X1,Y1,X2,Y2 coordinates for a rectangle
2540 which encloses the item identified by index in ARGS."""
2541 return self._getints(
2542 self.tk.call((self._w, 'bbox') + args)) or None
2543 def curselection(self):
2544 """Return list of indices of currently selected item."""
2545 # XXX Ought to apply self._getints()...
2546 return self.tk.splitlist(self.tk.call(
2547 self._w, 'curselection'))
2548 def delete(self, first, last=None):
2549 """Delete items from FIRST to LAST (not included)."""
2550 self.tk.call(self._w, 'delete', first, last)
2551 def get(self, first, last=None):
2552 """Get list of items from FIRST to LAST (not included)."""
2553 if last:
2554 return self.tk.splitlist(self.tk.call(
2555 self._w, 'get', first, last))
2556 else:
2557 return self.tk.call(self._w, 'get', first)
2558 def index(self, index):
2559 """Return index of item identified with INDEX."""
2560 i = self.tk.call(self._w, 'index', index)
2561 if i == 'none': return None
2562 return getint(i)
2563 def insert(self, index, *elements):
2564 """Insert ELEMENTS at INDEX."""
2565 self.tk.call((self._w, 'insert', index) + elements)
2566 def nearest(self, y):
2567 """Get index of item which is nearest to y coordinate Y."""
2568 return getint(self.tk.call(
2569 self._w, 'nearest', y))
2570 def scan_mark(self, x, y):
2571 """Remember the current X, Y coordinates."""
2572 self.tk.call(self._w, 'scan', 'mark', x, y)
2573 def scan_dragto(self, x, y):
2574 """Adjust the view of the listbox to 10 times the
2575 difference between X and Y and the coordinates given in
2576 scan_mark."""
2577 self.tk.call(self._w, 'scan', 'dragto', x, y)
2578 def see(self, index):
2579 """Scroll such that INDEX is visible."""
2580 self.tk.call(self._w, 'see', index)
2581 def selection_anchor(self, index):
2582 """Set the fixed end oft the selection to INDEX."""
2583 self.tk.call(self._w, 'selection', 'anchor', index)
2584 select_anchor = selection_anchor
2585 def selection_clear(self, first, last=None):
2586 """Clear the selection from FIRST to LAST (not included)."""
2587 self.tk.call(self._w,
2588 'selection', 'clear', first, last)
2589 select_clear = selection_clear
2590 def selection_includes(self, index):
2591 """Return 1 if INDEX is part of the selection."""
2592 return self.tk.getboolean(self.tk.call(
2593 self._w, 'selection', 'includes', index))
2594 select_includes = selection_includes
2595 def selection_set(self, first, last=None):
2596 """Set the selection from FIRST to LAST (not included) without
2597 changing the currently selected elements."""
2598 self.tk.call(self._w, 'selection', 'set', first, last)
2599 select_set = selection_set
2600 def size(self):
2601 """Return the number of elements in the listbox."""
2602 return getint(self.tk.call(self._w, 'size'))
Guido van Rossum09f1ad82001-09-05 19:29:56 +00002603 def itemcget(self, index, option):
2604 """Return the resource value for an ITEM and an OPTION."""
2605 return self.tk.call(
2606 (self._w, 'itemcget') + (index, '-'+option))
Guido van Rossuma0adb922001-09-01 18:29:55 +00002607 def itemconfigure(self, index, cnf=None, **kw):
Guido van Rossum09f1ad82001-09-05 19:29:56 +00002608 """Configure resources of an ITEM.
Guido van Rossuma0adb922001-09-01 18:29:55 +00002609
2610 The values for resources are specified as keyword arguments.
2611 To get an overview about the allowed keyword arguments
2612 call the method without arguments.
2613 Valid resource names: background, bg, foreground, fg,
2614 selectbackground, selectforeground."""
Martin v. Löwis6ce13152002-10-10 14:36:13 +00002615 return self._configure(('itemconfigure', index), cnf, kw)
Guido van Rossuma0adb922001-09-01 18:29:55 +00002616 itemconfig = itemconfigure
Guido van Rossum18468821994-06-20 07:49:28 +00002617
2618class Menu(Widget):
Fredrik Lundh06d28152000-08-09 18:03:12 +00002619 """Menu widget which allows to display menu bars, pull-down menus and pop-up menus."""
2620 def __init__(self, master=None, cnf={}, **kw):
2621 """Construct menu widget with the parent MASTER.
Guido van Rossum5917ecb2000-06-29 16:30:50 +00002622
Fredrik Lundh06d28152000-08-09 18:03:12 +00002623 Valid resource names: activebackground, activeborderwidth,
2624 activeforeground, background, bd, bg, borderwidth, cursor,
2625 disabledforeground, fg, font, foreground, postcommand, relief,
2626 selectcolor, takefocus, tearoff, tearoffcommand, title, type."""
2627 Widget.__init__(self, master, 'menu', cnf, kw)
2628 def tk_bindForTraversal(self):
2629 pass # obsolete since Tk 4.0
2630 def tk_mbPost(self):
2631 self.tk.call('tk_mbPost', self._w)
2632 def tk_mbUnpost(self):
2633 self.tk.call('tk_mbUnpost')
2634 def tk_traverseToMenu(self, char):
2635 self.tk.call('tk_traverseToMenu', self._w, char)
2636 def tk_traverseWithinMenu(self, char):
2637 self.tk.call('tk_traverseWithinMenu', self._w, char)
2638 def tk_getMenuButtons(self):
2639 return self.tk.call('tk_getMenuButtons', self._w)
2640 def tk_nextMenu(self, count):
2641 self.tk.call('tk_nextMenu', count)
2642 def tk_nextMenuEntry(self, count):
2643 self.tk.call('tk_nextMenuEntry', count)
2644 def tk_invokeMenu(self):
2645 self.tk.call('tk_invokeMenu', self._w)
2646 def tk_firstMenu(self):
2647 self.tk.call('tk_firstMenu', self._w)
2648 def tk_mbButtonDown(self):
2649 self.tk.call('tk_mbButtonDown', self._w)
2650 def tk_popup(self, x, y, entry=""):
2651 """Post the menu at position X,Y with entry ENTRY."""
2652 self.tk.call('tk_popup', self._w, x, y, entry)
2653 def activate(self, index):
2654 """Activate entry at INDEX."""
2655 self.tk.call(self._w, 'activate', index)
2656 def add(self, itemType, cnf={}, **kw):
2657 """Internal function."""
2658 self.tk.call((self._w, 'add', itemType) +
2659 self._options(cnf, kw))
2660 def add_cascade(self, cnf={}, **kw):
2661 """Add hierarchical menu item."""
2662 self.add('cascade', cnf or kw)
2663 def add_checkbutton(self, cnf={}, **kw):
2664 """Add checkbutton menu item."""
2665 self.add('checkbutton', cnf or kw)
2666 def add_command(self, cnf={}, **kw):
2667 """Add command menu item."""
2668 self.add('command', cnf or kw)
2669 def add_radiobutton(self, cnf={}, **kw):
2670 """Addd radio menu item."""
2671 self.add('radiobutton', cnf or kw)
2672 def add_separator(self, cnf={}, **kw):
2673 """Add separator."""
2674 self.add('separator', cnf or kw)
2675 def insert(self, index, itemType, cnf={}, **kw):
2676 """Internal function."""
2677 self.tk.call((self._w, 'insert', index, itemType) +
2678 self._options(cnf, kw))
2679 def insert_cascade(self, index, cnf={}, **kw):
2680 """Add hierarchical menu item at INDEX."""
2681 self.insert(index, 'cascade', cnf or kw)
2682 def insert_checkbutton(self, index, cnf={}, **kw):
2683 """Add checkbutton menu item at INDEX."""
2684 self.insert(index, 'checkbutton', cnf or kw)
2685 def insert_command(self, index, cnf={}, **kw):
2686 """Add command menu item at INDEX."""
2687 self.insert(index, 'command', cnf or kw)
2688 def insert_radiobutton(self, index, cnf={}, **kw):
2689 """Addd radio menu item at INDEX."""
2690 self.insert(index, 'radiobutton', cnf or kw)
2691 def insert_separator(self, index, cnf={}, **kw):
2692 """Add separator at INDEX."""
2693 self.insert(index, 'separator', cnf or kw)
2694 def delete(self, index1, index2=None):
Hirokazu Yamamotoa18424c2008-11-04 06:26:27 +00002695 """Delete menu items between INDEX1 and INDEX2 (included)."""
Robert Schuppenies3d1c7de2008-08-10 11:28:17 +00002696 if index2 is None:
2697 index2 = index1
Robert Schuppenies3d1c7de2008-08-10 11:28:17 +00002698
Hirokazu Yamamotoa18424c2008-11-04 06:26:27 +00002699 num_index1, num_index2 = self.index(index1), self.index(index2)
2700 if (num_index1 is None) or (num_index2 is None):
2701 num_index1, num_index2 = 0, -1
2702
2703 for i in range(num_index1, num_index2 + 1):
2704 if 'command' in self.entryconfig(i):
2705 c = str(self.entrycget(i, 'command'))
2706 if c:
2707 self.deletecommand(c)
2708 self.tk.call(self._w, 'delete', index1, index2)
Fredrik Lundh06d28152000-08-09 18:03:12 +00002709 def entrycget(self, index, option):
2710 """Return the resource value of an menu item for OPTION at INDEX."""
2711 return self.tk.call(self._w, 'entrycget', index, '-' + option)
2712 def entryconfigure(self, index, cnf=None, **kw):
2713 """Configure a menu item at INDEX."""
Martin v. Löwis6ce13152002-10-10 14:36:13 +00002714 return self._configure(('entryconfigure', index), cnf, kw)
Fredrik Lundh06d28152000-08-09 18:03:12 +00002715 entryconfig = entryconfigure
2716 def index(self, index):
2717 """Return the index of a menu item identified by INDEX."""
2718 i = self.tk.call(self._w, 'index', index)
2719 if i == 'none': return None
2720 return getint(i)
2721 def invoke(self, index):
2722 """Invoke a menu item identified by INDEX and execute
2723 the associated command."""
2724 return self.tk.call(self._w, 'invoke', index)
2725 def post(self, x, y):
2726 """Display a menu at position X,Y."""
2727 self.tk.call(self._w, 'post', x, y)
2728 def type(self, index):
2729 """Return the type of the menu item at INDEX."""
2730 return self.tk.call(self._w, 'type', index)
2731 def unpost(self):
2732 """Unmap a menu."""
2733 self.tk.call(self._w, 'unpost')
Martin v. Löwis5c3c4242012-03-13 13:40:42 -07002734 def xposition(self, index): # new in Tk 8.5
2735 """Return the x-position of the leftmost pixel of the menu item
2736 at INDEX."""
2737 return getint(self.tk.call(self._w, 'xposition', index))
Fredrik Lundh06d28152000-08-09 18:03:12 +00002738 def yposition(self, index):
2739 """Return the y-position of the topmost pixel of the menu item at INDEX."""
2740 return getint(self.tk.call(
2741 self._w, 'yposition', index))
Guido van Rossum18468821994-06-20 07:49:28 +00002742
2743class Menubutton(Widget):
Fredrik Lundh06d28152000-08-09 18:03:12 +00002744 """Menubutton widget, obsolete since Tk8.0."""
2745 def __init__(self, master=None, cnf={}, **kw):
2746 Widget.__init__(self, master, 'menubutton', cnf, kw)
Guido van Rossum18468821994-06-20 07:49:28 +00002747
2748class Message(Widget):
Fredrik Lundh06d28152000-08-09 18:03:12 +00002749 """Message widget to display multiline text. Obsolete since Label does it too."""
2750 def __init__(self, master=None, cnf={}, **kw):
2751 Widget.__init__(self, master, 'message', cnf, kw)
Guido van Rossum18468821994-06-20 07:49:28 +00002752
2753class Radiobutton(Widget):
Fredrik Lundh06d28152000-08-09 18:03:12 +00002754 """Radiobutton widget which shows only one of several buttons in on-state."""
2755 def __init__(self, master=None, cnf={}, **kw):
2756 """Construct a radiobutton widget with the parent MASTER.
Guido van Rossum5917ecb2000-06-29 16:30:50 +00002757
Fredrik Lundh06d28152000-08-09 18:03:12 +00002758 Valid resource names: activebackground, activeforeground, anchor,
2759 background, bd, bg, bitmap, borderwidth, command, cursor,
2760 disabledforeground, fg, font, foreground, height,
2761 highlightbackground, highlightcolor, highlightthickness, image,
2762 indicatoron, justify, padx, pady, relief, selectcolor, selectimage,
2763 state, takefocus, text, textvariable, underline, value, variable,
2764 width, wraplength."""
2765 Widget.__init__(self, master, 'radiobutton', cnf, kw)
2766 def deselect(self):
2767 """Put the button in off-state."""
Guido van Rossum5917ecb2000-06-29 16:30:50 +00002768
Fredrik Lundh06d28152000-08-09 18:03:12 +00002769 self.tk.call(self._w, 'deselect')
2770 def flash(self):
2771 """Flash the button."""
2772 self.tk.call(self._w, 'flash')
2773 def invoke(self):
2774 """Toggle the button and invoke a command if given as resource."""
2775 return self.tk.call(self._w, 'invoke')
2776 def select(self):
2777 """Put the button in on-state."""
2778 self.tk.call(self._w, 'select')
Guido van Rossum18468821994-06-20 07:49:28 +00002779
2780class Scale(Widget):
Fredrik Lundh06d28152000-08-09 18:03:12 +00002781 """Scale widget which can display a numerical scale."""
2782 def __init__(self, master=None, cnf={}, **kw):
2783 """Construct a scale widget with the parent MASTER.
Guido van Rossum5917ecb2000-06-29 16:30:50 +00002784
Fredrik Lundh06d28152000-08-09 18:03:12 +00002785 Valid resource names: activebackground, background, bigincrement, bd,
2786 bg, borderwidth, command, cursor, digits, fg, font, foreground, from,
2787 highlightbackground, highlightcolor, highlightthickness, label,
2788 length, orient, relief, repeatdelay, repeatinterval, resolution,
2789 showvalue, sliderlength, sliderrelief, state, takefocus,
2790 tickinterval, to, troughcolor, variable, width."""
2791 Widget.__init__(self, master, 'scale', cnf, kw)
2792 def get(self):
2793 """Get the current value as integer or float."""
2794 value = self.tk.call(self._w, 'get')
2795 try:
2796 return getint(value)
2797 except ValueError:
2798 return getdouble(value)
2799 def set(self, value):
2800 """Set the value to VALUE."""
2801 self.tk.call(self._w, 'set', value)
2802 def coords(self, value=None):
2803 """Return a tuple (X,Y) of the point along the centerline of the
2804 trough that corresponds to VALUE or the current value if None is
2805 given."""
2806
2807 return self._getints(self.tk.call(self._w, 'coords', value))
2808 def identify(self, x, y):
2809 """Return where the point X,Y lies. Valid return values are "slider",
2810 "though1" and "though2"."""
2811 return self.tk.call(self._w, 'identify', x, y)
Guido van Rossum18468821994-06-20 07:49:28 +00002812
2813class Scrollbar(Widget):
Fredrik Lundh06d28152000-08-09 18:03:12 +00002814 """Scrollbar widget which displays a slider at a certain position."""
2815 def __init__(self, master=None, cnf={}, **kw):
2816 """Construct a scrollbar widget with the parent MASTER.
Guido van Rossum5917ecb2000-06-29 16:30:50 +00002817
Fredrik Lundh06d28152000-08-09 18:03:12 +00002818 Valid resource names: activebackground, activerelief,
2819 background, bd, bg, borderwidth, command, cursor,
2820 elementborderwidth, highlightbackground,
2821 highlightcolor, highlightthickness, jump, orient,
2822 relief, repeatdelay, repeatinterval, takefocus,
2823 troughcolor, width."""
2824 Widget.__init__(self, master, 'scrollbar', cnf, kw)
2825 def activate(self, index):
2826 """Display the element at INDEX with activebackground and activerelief.
2827 INDEX can be "arrow1","slider" or "arrow2"."""
2828 self.tk.call(self._w, 'activate', index)
2829 def delta(self, deltax, deltay):
2830 """Return the fractional change of the scrollbar setting if it
2831 would be moved by DELTAX or DELTAY pixels."""
2832 return getdouble(
2833 self.tk.call(self._w, 'delta', deltax, deltay))
2834 def fraction(self, x, y):
2835 """Return the fractional value which corresponds to a slider
2836 position of X,Y."""
2837 return getdouble(self.tk.call(self._w, 'fraction', x, y))
2838 def identify(self, x, y):
2839 """Return the element under position X,Y as one of
2840 "arrow1","slider","arrow2" or ""."""
2841 return self.tk.call(self._w, 'identify', x, y)
2842 def get(self):
2843 """Return the current fractional values (upper and lower end)
2844 of the slider position."""
2845 return self._getdoubles(self.tk.call(self._w, 'get'))
2846 def set(self, *args):
2847 """Set the fractional values of the slider position (upper and
2848 lower ends as value between 0 and 1)."""
2849 self.tk.call((self._w, 'set') + args)
Raymond Hettingerff41c482003-04-06 09:01:11 +00002850
2851
2852
Guilherme Polo1fff0082009-08-14 15:05:30 +00002853class Text(Widget, XView, YView):
Fredrik Lundh06d28152000-08-09 18:03:12 +00002854 """Text widget which can display text in various forms."""
Fredrik Lundh06d28152000-08-09 18:03:12 +00002855 def __init__(self, master=None, cnf={}, **kw):
2856 """Construct a text widget with the parent MASTER.
Raymond Hettingerff41c482003-04-06 09:01:11 +00002857
Martin v. Löwis2ec36272002-10-13 10:22:08 +00002858 STANDARD OPTIONS
Raymond Hettingerff41c482003-04-06 09:01:11 +00002859
Martin v. Löwis2ec36272002-10-13 10:22:08 +00002860 background, borderwidth, cursor,
2861 exportselection, font, foreground,
2862 highlightbackground, highlightcolor,
2863 highlightthickness, insertbackground,
2864 insertborderwidth, insertofftime,
2865 insertontime, insertwidth, padx, pady,
Raymond Hettingerff41c482003-04-06 09:01:11 +00002866 relief, selectbackground,
Martin v. Löwis2ec36272002-10-13 10:22:08 +00002867 selectborderwidth, selectforeground,
Raymond Hettingerff41c482003-04-06 09:01:11 +00002868 setgrid, takefocus,
Martin v. Löwis2ec36272002-10-13 10:22:08 +00002869 xscrollcommand, yscrollcommand,
Guido van Rossum5917ecb2000-06-29 16:30:50 +00002870
Martin v. Löwis2ec36272002-10-13 10:22:08 +00002871 WIDGET-SPECIFIC OPTIONS
Raymond Hettingerff41c482003-04-06 09:01:11 +00002872
Martin v. Löwis2ec36272002-10-13 10:22:08 +00002873 autoseparators, height, maxundo,
Raymond Hettingerff41c482003-04-06 09:01:11 +00002874 spacing1, spacing2, spacing3,
Martin v. Löwis2ec36272002-10-13 10:22:08 +00002875 state, tabs, undo, width, wrap,
Raymond Hettingerff41c482003-04-06 09:01:11 +00002876
Martin v. Löwis2ec36272002-10-13 10:22:08 +00002877 """
Fredrik Lundh06d28152000-08-09 18:03:12 +00002878 Widget.__init__(self, master, 'text', cnf, kw)
2879 def bbox(self, *args):
2880 """Return a tuple of (x,y,width,height) which gives the bounding
2881 box of the visible part of the character at the index in ARGS."""
2882 return self._getints(
2883 self.tk.call((self._w, 'bbox') + args)) or None
2884 def tk_textSelectTo(self, index):
2885 self.tk.call('tk_textSelectTo', self._w, index)
2886 def tk_textBackspace(self):
2887 self.tk.call('tk_textBackspace', self._w)
2888 def tk_textIndexCloser(self, a, b, c):
2889 self.tk.call('tk_textIndexCloser', self._w, a, b, c)
2890 def tk_textResetAnchor(self, index):
2891 self.tk.call('tk_textResetAnchor', self._w, index)
2892 def compare(self, index1, op, index2):
2893 """Return whether between index INDEX1 and index INDEX2 the
2894 relation OP is satisfied. OP is one of <, <=, ==, >=, >, or !=."""
2895 return self.tk.getboolean(self.tk.call(
2896 self._w, 'compare', index1, op, index2))
Martin v. Löwis5c3c4242012-03-13 13:40:42 -07002897 def count(self, index1, index2, *args): # new in Tk 8.5
2898 """Counts the number of relevant things between the two indices.
2899 If index1 is after index2, the result will be a negative number
2900 (and this holds for each of the possible options).
2901
2902 The actual items which are counted depends on the options given by
2903 args. The result is a list of integers, one for the result of each
2904 counting option given. Valid counting options are "chars",
2905 "displaychars", "displayindices", "displaylines", "indices",
2906 "lines", "xpixels" and "ypixels". There is an additional possible
2907 option "update", which if given then all subsequent options ensure
2908 that any possible out of date information is recalculated."""
2909 args = ['-%s' % arg for arg in args if not arg.startswith('-')]
2910 args += [index1, index2]
2911 res = self.tk.call(self._w, 'count', *args) or None
2912 if res is not None and len(args) <= 3:
2913 return (res, )
2914 else:
2915 return res
Fredrik Lundh06d28152000-08-09 18:03:12 +00002916 def debug(self, boolean=None):
2917 """Turn on the internal consistency checks of the B-Tree inside the text
2918 widget according to BOOLEAN."""
2919 return self.tk.getboolean(self.tk.call(
2920 self._w, 'debug', boolean))
2921 def delete(self, index1, index2=None):
2922 """Delete the characters between INDEX1 and INDEX2 (not included)."""
2923 self.tk.call(self._w, 'delete', index1, index2)
2924 def dlineinfo(self, index):
2925 """Return tuple (x,y,width,height,baseline) giving the bounding box
2926 and baseline position of the visible part of the line containing
2927 the character at INDEX."""
2928 return self._getints(self.tk.call(self._w, 'dlineinfo', index))
Guido van Rossum256705b2002-04-23 13:29:43 +00002929 def dump(self, index1, index2=None, command=None, **kw):
2930 """Return the contents of the widget between index1 and index2.
Raymond Hettingerff41c482003-04-06 09:01:11 +00002931
Guido van Rossum256705b2002-04-23 13:29:43 +00002932 The type of contents returned in filtered based on the keyword
2933 parameters; if 'all', 'image', 'mark', 'tag', 'text', or 'window' are
2934 given and true, then the corresponding items are returned. The result
2935 is a list of triples of the form (key, value, index). If none of the
2936 keywords are true then 'all' is used by default.
Raymond Hettingerff41c482003-04-06 09:01:11 +00002937
Guido van Rossum256705b2002-04-23 13:29:43 +00002938 If the 'command' argument is given, it is called once for each element
2939 of the list of triples, with the values of each triple serving as the
2940 arguments to the function. In this case the list is not returned."""
2941 args = []
2942 func_name = None
2943 result = None
2944 if not command:
2945 # Never call the dump command without the -command flag, since the
2946 # output could involve Tcl quoting and would be a pain to parse
2947 # right. Instead just set the command to build a list of triples
2948 # as if we had done the parsing.
2949 result = []
2950 def append_triple(key, value, index, result=result):
2951 result.append((key, value, index))
2952 command = append_triple
2953 try:
2954 if not isinstance(command, str):
2955 func_name = command = self._register(command)
2956 args += ["-command", command]
2957 for key in kw:
2958 if kw[key]: args.append("-" + key)
2959 args.append(index1)
2960 if index2:
2961 args.append(index2)
2962 self.tk.call(self._w, "dump", *args)
2963 return result
2964 finally:
2965 if func_name:
2966 self.deletecommand(func_name)
Raymond Hettingerff41c482003-04-06 09:01:11 +00002967
Martin v. Löwis2ec36272002-10-13 10:22:08 +00002968 ## new in tk8.4
2969 def edit(self, *args):
2970 """Internal method
Raymond Hettingerff41c482003-04-06 09:01:11 +00002971
2972 This method controls the undo mechanism and
2973 the modified flag. The exact behavior of the
2974 command depends on the option argument that
2975 follows the edit argument. The following forms
Martin v. Löwis2ec36272002-10-13 10:22:08 +00002976 of the command are currently supported:
Raymond Hettingerff41c482003-04-06 09:01:11 +00002977
Martin v. Löwis2ec36272002-10-13 10:22:08 +00002978 edit_modified, edit_redo, edit_reset, edit_separator
2979 and edit_undo
Raymond Hettingerff41c482003-04-06 09:01:11 +00002980
Martin v. Löwis2ec36272002-10-13 10:22:08 +00002981 """
Georg Brandlb533e262008-05-25 18:19:30 +00002982 return self.tk.call(self._w, 'edit', *args)
Martin v. Löwis2ec36272002-10-13 10:22:08 +00002983
2984 def edit_modified(self, arg=None):
2985 """Get or Set the modified flag
Raymond Hettingerff41c482003-04-06 09:01:11 +00002986
Martin v. Löwis2ec36272002-10-13 10:22:08 +00002987 If arg is not specified, returns the modified
Raymond Hettingerff41c482003-04-06 09:01:11 +00002988 flag of the widget. The insert, delete, edit undo and
2989 edit redo commands or the user can set or clear the
2990 modified flag. If boolean is specified, sets the
Martin v. Löwis2ec36272002-10-13 10:22:08 +00002991 modified flag of the widget to arg.
2992 """
2993 return self.edit("modified", arg)
Raymond Hettingerff41c482003-04-06 09:01:11 +00002994
Martin v. Löwis2ec36272002-10-13 10:22:08 +00002995 def edit_redo(self):
2996 """Redo the last undone edit
Raymond Hettingerff41c482003-04-06 09:01:11 +00002997
2998 When the undo option is true, reapplies the last
2999 undone edits provided no other edits were done since
Martin v. Löwis2ec36272002-10-13 10:22:08 +00003000 then. Generates an error when the redo stack is empty.
3001 Does nothing when the undo option is false.
3002 """
3003 return self.edit("redo")
Raymond Hettingerff41c482003-04-06 09:01:11 +00003004
Martin v. Löwis2ec36272002-10-13 10:22:08 +00003005 def edit_reset(self):
3006 """Clears the undo and redo stacks
3007 """
3008 return self.edit("reset")
Raymond Hettingerff41c482003-04-06 09:01:11 +00003009
Martin v. Löwis2ec36272002-10-13 10:22:08 +00003010 def edit_separator(self):
Raymond Hettingerff41c482003-04-06 09:01:11 +00003011 """Inserts a separator (boundary) on the undo stack.
3012
Martin v. Löwis2ec36272002-10-13 10:22:08 +00003013 Does nothing when the undo option is false
3014 """
3015 return self.edit("separator")
Raymond Hettingerff41c482003-04-06 09:01:11 +00003016
Martin v. Löwis2ec36272002-10-13 10:22:08 +00003017 def edit_undo(self):
Raymond Hettingerff41c482003-04-06 09:01:11 +00003018 """Undoes the last edit action
3019
3020 If the undo option is true. An edit action is defined
3021 as all the insert and delete commands that are recorded
3022 on the undo stack in between two separators. Generates
3023 an error when the undo stack is empty. Does nothing
Martin v. Löwis2ec36272002-10-13 10:22:08 +00003024 when the undo option is false
3025 """
3026 return self.edit("undo")
Raymond Hettingerff41c482003-04-06 09:01:11 +00003027
Fredrik Lundh06d28152000-08-09 18:03:12 +00003028 def get(self, index1, index2=None):
3029 """Return the text from INDEX1 to INDEX2 (not included)."""
3030 return self.tk.call(self._w, 'get', index1, index2)
3031 # (Image commands are new in 8.0)
3032 def image_cget(self, index, option):
3033 """Return the value of OPTION of an embedded image at INDEX."""
3034 if option[:1] != "-":
3035 option = "-" + option
3036 if option[-1:] == "_":
3037 option = option[:-1]
3038 return self.tk.call(self._w, "image", "cget", index, option)
Martin v. Löwis6ce13152002-10-10 14:36:13 +00003039 def image_configure(self, index, cnf=None, **kw):
Fredrik Lundh06d28152000-08-09 18:03:12 +00003040 """Configure an embedded image at INDEX."""
Martin v. Löwis6ce13152002-10-10 14:36:13 +00003041 return self._configure(('image', 'configure', index), cnf, kw)
Fredrik Lundh06d28152000-08-09 18:03:12 +00003042 def image_create(self, index, cnf={}, **kw):
3043 """Create an embedded image at INDEX."""
Raymond Hettingerff41c482003-04-06 09:01:11 +00003044 return self.tk.call(
3045 self._w, "image", "create", index,
3046 *self._options(cnf, kw))
Fredrik Lundh06d28152000-08-09 18:03:12 +00003047 def image_names(self):
3048 """Return all names of embedded images in this widget."""
3049 return self.tk.call(self._w, "image", "names")
3050 def index(self, index):
3051 """Return the index in the form line.char for INDEX."""
Christian Heimes57dddfb2008-01-02 18:30:52 +00003052 return str(self.tk.call(self._w, 'index', index))
Fredrik Lundh06d28152000-08-09 18:03:12 +00003053 def insert(self, index, chars, *args):
3054 """Insert CHARS before the characters at INDEX. An additional
3055 tag can be given in ARGS. Additional CHARS and tags can follow in ARGS."""
3056 self.tk.call((self._w, 'insert', index, chars) + args)
3057 def mark_gravity(self, markName, direction=None):
3058 """Change the gravity of a mark MARKNAME to DIRECTION (LEFT or RIGHT).
3059 Return the current value if None is given for DIRECTION."""
3060 return self.tk.call(
3061 (self._w, 'mark', 'gravity', markName, direction))
3062 def mark_names(self):
3063 """Return all mark names."""
3064 return self.tk.splitlist(self.tk.call(
3065 self._w, 'mark', 'names'))
3066 def mark_set(self, markName, index):
3067 """Set mark MARKNAME before the character at INDEX."""
3068 self.tk.call(self._w, 'mark', 'set', markName, index)
3069 def mark_unset(self, *markNames):
3070 """Delete all marks in MARKNAMES."""
3071 self.tk.call((self._w, 'mark', 'unset') + markNames)
3072 def mark_next(self, index):
3073 """Return the name of the next mark after INDEX."""
3074 return self.tk.call(self._w, 'mark', 'next', index) or None
3075 def mark_previous(self, index):
3076 """Return the name of the previous mark before INDEX."""
3077 return self.tk.call(self._w, 'mark', 'previous', index) or None
Martin v. Löwis5c3c4242012-03-13 13:40:42 -07003078 def peer_create(self, newPathName, cnf={}, **kw): # new in Tk 8.5
3079 """Creates a peer text widget with the given newPathName, and any
3080 optional standard configuration options. By default the peer will
3081 have the same start and and end line as the parent widget, but
3082 these can be overriden with the standard configuration options."""
3083 self.tk.call(self._w, 'peer', 'create', newPathName,
3084 *self._options(cnf, kw))
3085 def peer_names(self): # new in Tk 8.5
3086 """Returns a list of peers of this widget (this does not include
3087 the widget itself)."""
3088 return self.tk.splitlist(self.tk.call(self._w, 'peer', 'names'))
3089 def replace(self, index1, index2, chars, *args): # new in Tk 8.5
3090 """Replaces the range of characters between index1 and index2 with
3091 the given characters and tags specified by args.
3092
3093 See the method insert for some more information about args, and the
3094 method delete for information about the indices."""
3095 self.tk.call(self._w, 'replace', index1, index2, chars, *args)
Fredrik Lundh06d28152000-08-09 18:03:12 +00003096 def scan_mark(self, x, y):
3097 """Remember the current X, Y coordinates."""
3098 self.tk.call(self._w, 'scan', 'mark', x, y)
3099 def scan_dragto(self, x, y):
3100 """Adjust the view of the text to 10 times the
3101 difference between X and Y and the coordinates given in
3102 scan_mark."""
3103 self.tk.call(self._w, 'scan', 'dragto', x, y)
3104 def search(self, pattern, index, stopindex=None,
3105 forwards=None, backwards=None, exact=None,
Thomas Wouters89f507f2006-12-13 04:49:30 +00003106 regexp=None, nocase=None, count=None, elide=None):
Fredrik Lundh06d28152000-08-09 18:03:12 +00003107 """Search PATTERN beginning from INDEX until STOPINDEX.
Guilherme Poloae098992009-02-09 16:44:24 +00003108 Return the index of the first character of a match or an
3109 empty string."""
Fredrik Lundh06d28152000-08-09 18:03:12 +00003110 args = [self._w, 'search']
3111 if forwards: args.append('-forwards')
3112 if backwards: args.append('-backwards')
3113 if exact: args.append('-exact')
3114 if regexp: args.append('-regexp')
3115 if nocase: args.append('-nocase')
Thomas Wouters89f507f2006-12-13 04:49:30 +00003116 if elide: args.append('-elide')
Fredrik Lundh06d28152000-08-09 18:03:12 +00003117 if count: args.append('-count'); args.append(count)
Guilherme Poloae098992009-02-09 16:44:24 +00003118 if pattern and pattern[0] == '-': args.append('--')
Fredrik Lundh06d28152000-08-09 18:03:12 +00003119 args.append(pattern)
3120 args.append(index)
3121 if stopindex: args.append(stopindex)
Guilherme Polo56f5be52009-03-07 01:54:57 +00003122 return str(self.tk.call(tuple(args)))
Fredrik Lundh06d28152000-08-09 18:03:12 +00003123 def see(self, index):
3124 """Scroll such that the character at INDEX is visible."""
3125 self.tk.call(self._w, 'see', index)
3126 def tag_add(self, tagName, index1, *args):
3127 """Add tag TAGNAME to all characters between INDEX1 and index2 in ARGS.
3128 Additional pairs of indices may follow in ARGS."""
3129 self.tk.call(
3130 (self._w, 'tag', 'add', tagName, index1) + args)
3131 def tag_unbind(self, tagName, sequence, funcid=None):
3132 """Unbind for all characters with TAGNAME for event SEQUENCE the
3133 function identified with FUNCID."""
3134 self.tk.call(self._w, 'tag', 'bind', tagName, sequence, '')
3135 if funcid:
3136 self.deletecommand(funcid)
3137 def tag_bind(self, tagName, sequence, func, add=None):
3138 """Bind to all characters with TAGNAME at event SEQUENCE a call to function FUNC.
Guido van Rossum5917ecb2000-06-29 16:30:50 +00003139
Fredrik Lundh06d28152000-08-09 18:03:12 +00003140 An additional boolean parameter ADD specifies whether FUNC will be
3141 called additionally to the other bound function or whether it will
3142 replace the previous function. See bind for the return value."""
3143 return self._bind((self._w, 'tag', 'bind', tagName),
3144 sequence, func, add)
3145 def tag_cget(self, tagName, option):
3146 """Return the value of OPTION for tag TAGNAME."""
3147 if option[:1] != '-':
3148 option = '-' + option
3149 if option[-1:] == '_':
3150 option = option[:-1]
3151 return self.tk.call(self._w, 'tag', 'cget', tagName, option)
Martin v. Löwis6ce13152002-10-10 14:36:13 +00003152 def tag_configure(self, tagName, cnf=None, **kw):
Fredrik Lundh06d28152000-08-09 18:03:12 +00003153 """Configure a tag TAGNAME."""
Martin v. Löwis6ce13152002-10-10 14:36:13 +00003154 return self._configure(('tag', 'configure', tagName), cnf, kw)
Fredrik Lundh06d28152000-08-09 18:03:12 +00003155 tag_config = tag_configure
3156 def tag_delete(self, *tagNames):
3157 """Delete all tags in TAGNAMES."""
3158 self.tk.call((self._w, 'tag', 'delete') + tagNames)
3159 def tag_lower(self, tagName, belowThis=None):
3160 """Change the priority of tag TAGNAME such that it is lower
3161 than the priority of BELOWTHIS."""
3162 self.tk.call(self._w, 'tag', 'lower', tagName, belowThis)
3163 def tag_names(self, index=None):
3164 """Return a list of all tag names."""
3165 return self.tk.splitlist(
3166 self.tk.call(self._w, 'tag', 'names', index))
3167 def tag_nextrange(self, tagName, index1, index2=None):
3168 """Return a list of start and end index for the first sequence of
3169 characters between INDEX1 and INDEX2 which all have tag TAGNAME.
3170 The text is searched forward from INDEX1."""
3171 return self.tk.splitlist(self.tk.call(
3172 self._w, 'tag', 'nextrange', tagName, index1, index2))
3173 def tag_prevrange(self, tagName, index1, index2=None):
3174 """Return a list of start and end index for the first sequence of
3175 characters between INDEX1 and INDEX2 which all have tag TAGNAME.
3176 The text is searched backwards from INDEX1."""
3177 return self.tk.splitlist(self.tk.call(
3178 self._w, 'tag', 'prevrange', tagName, index1, index2))
3179 def tag_raise(self, tagName, aboveThis=None):
3180 """Change the priority of tag TAGNAME such that it is higher
3181 than the priority of ABOVETHIS."""
3182 self.tk.call(
3183 self._w, 'tag', 'raise', tagName, aboveThis)
3184 def tag_ranges(self, tagName):
3185 """Return a list of ranges of text which have tag TAGNAME."""
3186 return self.tk.splitlist(self.tk.call(
3187 self._w, 'tag', 'ranges', tagName))
3188 def tag_remove(self, tagName, index1, index2=None):
3189 """Remove tag TAGNAME from all characters between INDEX1 and INDEX2."""
3190 self.tk.call(
3191 self._w, 'tag', 'remove', tagName, index1, index2)
3192 def window_cget(self, index, option):
3193 """Return the value of OPTION of an embedded window at INDEX."""
3194 if option[:1] != '-':
3195 option = '-' + option
3196 if option[-1:] == '_':
3197 option = option[:-1]
3198 return self.tk.call(self._w, 'window', 'cget', index, option)
Martin v. Löwis6ce13152002-10-10 14:36:13 +00003199 def window_configure(self, index, cnf=None, **kw):
Fredrik Lundh06d28152000-08-09 18:03:12 +00003200 """Configure an embedded window at INDEX."""
Martin v. Löwis6ce13152002-10-10 14:36:13 +00003201 return self._configure(('window', 'configure', index), cnf, kw)
Fredrik Lundh06d28152000-08-09 18:03:12 +00003202 window_config = window_configure
3203 def window_create(self, index, cnf={}, **kw):
3204 """Create a window at INDEX."""
3205 self.tk.call(
3206 (self._w, 'window', 'create', index)
3207 + self._options(cnf, kw))
3208 def window_names(self):
3209 """Return all names of embedded windows in this widget."""
3210 return self.tk.splitlist(
3211 self.tk.call(self._w, 'window', 'names'))
Fredrik Lundh06d28152000-08-09 18:03:12 +00003212 def yview_pickplace(self, *what):
3213 """Obsolete function, use see."""
3214 self.tk.call((self._w, 'yview', '-pickplace') + what)
Guido van Rossum18468821994-06-20 07:49:28 +00003215
Martin v. Löwis2ec36272002-10-13 10:22:08 +00003216
Guido van Rossum28574b51996-10-21 15:16:51 +00003217class _setit:
Fredrik Lundh06d28152000-08-09 18:03:12 +00003218 """Internal class. It wraps the command in the widget OptionMenu."""
3219 def __init__(self, var, value, callback=None):
3220 self.__value = value
3221 self.__var = var
3222 self.__callback = callback
3223 def __call__(self, *args):
3224 self.__var.set(self.__value)
3225 if self.__callback:
Raymond Hettingerff41c482003-04-06 09:01:11 +00003226 self.__callback(self.__value, *args)
Guido van Rossum28574b51996-10-21 15:16:51 +00003227
3228class OptionMenu(Menubutton):
Fredrik Lundh06d28152000-08-09 18:03:12 +00003229 """OptionMenu which allows the user to select a value from a menu."""
3230 def __init__(self, master, variable, value, *values, **kwargs):
3231 """Construct an optionmenu widget with the parent MASTER, with
3232 the resource textvariable set to VARIABLE, the initially selected
3233 value VALUE, the other menu values VALUES and an additional
3234 keyword argument command."""
3235 kw = {"borderwidth": 2, "textvariable": variable,
3236 "indicatoron": 1, "relief": RAISED, "anchor": "c",
3237 "highlightthickness": 2}
3238 Widget.__init__(self, master, "menubutton", kw)
3239 self.widgetName = 'tk_optionMenu'
3240 menu = self.__menu = Menu(self, name="menu", tearoff=0)
3241 self.menuname = menu._w
3242 # 'command' is the only supported keyword
3243 callback = kwargs.get('command')
Guido van Rossume014a132006-08-19 16:53:45 +00003244 if 'command' in kwargs:
Fredrik Lundh06d28152000-08-09 18:03:12 +00003245 del kwargs['command']
3246 if kwargs:
Collin Winterce36ad82007-08-30 01:19:48 +00003247 raise TclError('unknown option -'+kwargs.keys()[0])
Fredrik Lundh06d28152000-08-09 18:03:12 +00003248 menu.add_command(label=value,
3249 command=_setit(variable, value, callback))
3250 for v in values:
3251 menu.add_command(label=v,
3252 command=_setit(variable, v, callback))
3253 self["menu"] = menu
Guido van Rossum28574b51996-10-21 15:16:51 +00003254
Fredrik Lundh06d28152000-08-09 18:03:12 +00003255 def __getitem__(self, name):
3256 if name == 'menu':
3257 return self.__menu
3258 return Widget.__getitem__(self, name)
Guido van Rossum28574b51996-10-21 15:16:51 +00003259
Fredrik Lundh06d28152000-08-09 18:03:12 +00003260 def destroy(self):
3261 """Destroy this widget and the associated menu."""
3262 Menubutton.destroy(self)
3263 self.__menu = None
Guido van Rossumbf4d8f91995-09-01 20:35:37 +00003264
Guido van Rossum35f67fb1995-08-04 03:50:29 +00003265class Image:
Fredrik Lundh06d28152000-08-09 18:03:12 +00003266 """Base class for images."""
Martin v. Löwis0d8ce612000-09-08 16:28:30 +00003267 _last_id = 0
Fredrik Lundh06d28152000-08-09 18:03:12 +00003268 def __init__(self, imgtype, name=None, cnf={}, master=None, **kw):
3269 self.name = None
3270 if not master:
3271 master = _default_root
3272 if not master:
Collin Winterce36ad82007-08-30 01:19:48 +00003273 raise RuntimeError('Too early to create image')
Fredrik Lundh06d28152000-08-09 18:03:12 +00003274 self.tk = master.tk
3275 if not name:
Martin v. Löwis0d8ce612000-09-08 16:28:30 +00003276 Image._last_id += 1
Walter Dörwald70a6b492004-02-12 17:35:32 +00003277 name = "pyimage%r" % (Image._last_id,) # tk itself would use image<x>
Fredrik Lundh06d28152000-08-09 18:03:12 +00003278 # The following is needed for systems where id(x)
3279 # can return a negative number, such as Linux/m68k:
3280 if name[0] == '-': name = '_' + name[1:]
3281 if kw and cnf: cnf = _cnfmerge((cnf, kw))
3282 elif kw: cnf = kw
3283 options = ()
3284 for k, v in cnf.items():
Florent Xicluna5d1155c2011-10-28 14:45:05 +02003285 if callable(v):
Fredrik Lundh06d28152000-08-09 18:03:12 +00003286 v = self._register(v)
3287 options = options + ('-'+k, v)
3288 self.tk.call(('image', 'create', imgtype, name,) + options)
3289 self.name = name
3290 def __str__(self): return self.name
3291 def __del__(self):
3292 if self.name:
3293 try:
3294 self.tk.call('image', 'delete', self.name)
3295 except TclError:
3296 # May happen if the root was destroyed
3297 pass
3298 def __setitem__(self, key, value):
3299 self.tk.call(self.name, 'configure', '-'+key, value)
3300 def __getitem__(self, key):
3301 return self.tk.call(self.name, 'configure', '-'+key)
3302 def configure(self, **kw):
3303 """Configure the image."""
3304 res = ()
3305 for k, v in _cnfmerge(kw).items():
3306 if v is not None:
3307 if k[-1] == '_': k = k[:-1]
Florent Xicluna5d1155c2011-10-28 14:45:05 +02003308 if callable(v):
Fredrik Lundh06d28152000-08-09 18:03:12 +00003309 v = self._register(v)
3310 res = res + ('-'+k, v)
3311 self.tk.call((self.name, 'config') + res)
3312 config = configure
3313 def height(self):
3314 """Return the height of the image."""
3315 return getint(
3316 self.tk.call('image', 'height', self.name))
3317 def type(self):
3318 """Return the type of the imgage, e.g. "photo" or "bitmap"."""
3319 return self.tk.call('image', 'type', self.name)
3320 def width(self):
3321 """Return the width of the image."""
3322 return getint(
3323 self.tk.call('image', 'width', self.name))
Guido van Rossum35f67fb1995-08-04 03:50:29 +00003324
3325class PhotoImage(Image):
Fredrik Lundh06d28152000-08-09 18:03:12 +00003326 """Widget which can display colored images in GIF, PPM/PGM format."""
3327 def __init__(self, name=None, cnf={}, master=None, **kw):
3328 """Create an image with NAME.
Guido van Rossum5917ecb2000-06-29 16:30:50 +00003329
Fredrik Lundh06d28152000-08-09 18:03:12 +00003330 Valid resource names: data, format, file, gamma, height, palette,
3331 width."""
Raymond Hettingerff41c482003-04-06 09:01:11 +00003332 Image.__init__(self, 'photo', name, cnf, master, **kw)
Fredrik Lundh06d28152000-08-09 18:03:12 +00003333 def blank(self):
3334 """Display a transparent image."""
3335 self.tk.call(self.name, 'blank')
3336 def cget(self, option):
3337 """Return the value of OPTION."""
3338 return self.tk.call(self.name, 'cget', '-' + option)
3339 # XXX config
3340 def __getitem__(self, key):
3341 return self.tk.call(self.name, 'cget', '-' + key)
3342 # XXX copy -from, -to, ...?
3343 def copy(self):
3344 """Return a new PhotoImage with the same image as this widget."""
3345 destImage = PhotoImage()
3346 self.tk.call(destImage, 'copy', self.name)
3347 return destImage
3348 def zoom(self,x,y=''):
3349 """Return a new PhotoImage with the same image as this widget
3350 but zoom it with X and Y."""
3351 destImage = PhotoImage()
3352 if y=='': y=x
3353 self.tk.call(destImage, 'copy', self.name, '-zoom',x,y)
3354 return destImage
3355 def subsample(self,x,y=''):
3356 """Return a new PhotoImage based on the same image as this widget
3357 but use only every Xth or Yth pixel."""
3358 destImage = PhotoImage()
3359 if y=='': y=x
3360 self.tk.call(destImage, 'copy', self.name, '-subsample',x,y)
3361 return destImage
3362 def get(self, x, y):
3363 """Return the color (red, green, blue) of the pixel at X,Y."""
3364 return self.tk.call(self.name, 'get', x, y)
3365 def put(self, data, to=None):
Mark Dickinson934896d2009-02-21 20:59:32 +00003366 """Put row formatted colors to image starting from
Fredrik Lundh06d28152000-08-09 18:03:12 +00003367 position TO, e.g. image.put("{red green} {blue yellow}", to=(4,6))"""
3368 args = (self.name, 'put', data)
3369 if to:
3370 if to[0] == '-to':
3371 to = to[1:]
3372 args = args + ('-to',) + tuple(to)
3373 self.tk.call(args)
3374 # XXX read
3375 def write(self, filename, format=None, from_coords=None):
3376 """Write image to file FILENAME in FORMAT starting from
3377 position FROM_COORDS."""
3378 args = (self.name, 'write', filename)
3379 if format:
3380 args = args + ('-format', format)
3381 if from_coords:
3382 args = args + ('-from',) + tuple(from_coords)
3383 self.tk.call(args)
Guido van Rossum35f67fb1995-08-04 03:50:29 +00003384
3385class BitmapImage(Image):
Fredrik Lundh06d28152000-08-09 18:03:12 +00003386 """Widget which can display a bitmap."""
3387 def __init__(self, name=None, cnf={}, master=None, **kw):
3388 """Create a bitmap with NAME.
Guido van Rossum5917ecb2000-06-29 16:30:50 +00003389
Fredrik Lundh06d28152000-08-09 18:03:12 +00003390 Valid resource names: background, data, file, foreground, maskdata, maskfile."""
Raymond Hettingerff41c482003-04-06 09:01:11 +00003391 Image.__init__(self, 'bitmap', name, cnf, master, **kw)
Guido van Rossum35f67fb1995-08-04 03:50:29 +00003392
3393def image_names(): return _default_root.tk.call('image', 'names')
3394def image_types(): return _default_root.tk.call('image', 'types')
3395
Martin v. Löwis2ec36272002-10-13 10:22:08 +00003396
Guilherme Polo1fff0082009-08-14 15:05:30 +00003397class Spinbox(Widget, XView):
Martin v. Löwis2ec36272002-10-13 10:22:08 +00003398 """spinbox widget."""
3399 def __init__(self, master=None, cnf={}, **kw):
3400 """Construct a spinbox widget with the parent MASTER.
Raymond Hettingerff41c482003-04-06 09:01:11 +00003401
Martin v. Löwis2ec36272002-10-13 10:22:08 +00003402 STANDARD OPTIONS
Raymond Hettingerff41c482003-04-06 09:01:11 +00003403
Martin v. Löwis2ec36272002-10-13 10:22:08 +00003404 activebackground, background, borderwidth,
3405 cursor, exportselection, font, foreground,
3406 highlightbackground, highlightcolor,
3407 highlightthickness, insertbackground,
3408 insertborderwidth, insertofftime,
Raymond Hettingerff41c482003-04-06 09:01:11 +00003409 insertontime, insertwidth, justify, relief,
3410 repeatdelay, repeatinterval,
Martin v. Löwis2ec36272002-10-13 10:22:08 +00003411 selectbackground, selectborderwidth
3412 selectforeground, takefocus, textvariable
3413 xscrollcommand.
Raymond Hettingerff41c482003-04-06 09:01:11 +00003414
Martin v. Löwis2ec36272002-10-13 10:22:08 +00003415 WIDGET-SPECIFIC OPTIONS
Raymond Hettingerff41c482003-04-06 09:01:11 +00003416
3417 buttonbackground, buttoncursor,
3418 buttondownrelief, buttonuprelief,
3419 command, disabledbackground,
3420 disabledforeground, format, from,
3421 invalidcommand, increment,
3422 readonlybackground, state, to,
Martin v. Löwis2ec36272002-10-13 10:22:08 +00003423 validate, validatecommand values,
3424 width, wrap,
3425 """
3426 Widget.__init__(self, master, 'spinbox', cnf, kw)
Raymond Hettingerff41c482003-04-06 09:01:11 +00003427
Martin v. Löwis2ec36272002-10-13 10:22:08 +00003428 def bbox(self, index):
Raymond Hettingerff41c482003-04-06 09:01:11 +00003429 """Return a tuple of X1,Y1,X2,Y2 coordinates for a
3430 rectangle which encloses the character given by index.
3431
3432 The first two elements of the list give the x and y
3433 coordinates of the upper-left corner of the screen
3434 area covered by the character (in pixels relative
3435 to the widget) and the last two elements give the
3436 width and height of the character, in pixels. The
3437 bounding box may refer to a region outside the
Martin v. Löwis2ec36272002-10-13 10:22:08 +00003438 visible area of the window.
3439 """
3440 return self.tk.call(self._w, 'bbox', index)
Raymond Hettingerff41c482003-04-06 09:01:11 +00003441
Martin v. Löwis2ec36272002-10-13 10:22:08 +00003442 def delete(self, first, last=None):
3443 """Delete one or more elements of the spinbox.
Raymond Hettingerff41c482003-04-06 09:01:11 +00003444
3445 First is the index of the first character to delete,
3446 and last is the index of the character just after
3447 the last one to delete. If last isn't specified it
3448 defaults to first+1, i.e. a single character is
Martin v. Löwis2ec36272002-10-13 10:22:08 +00003449 deleted. This command returns an empty string.
3450 """
3451 return self.tk.call(self._w, 'delete', first, last)
Raymond Hettingerff41c482003-04-06 09:01:11 +00003452
Martin v. Löwis2ec36272002-10-13 10:22:08 +00003453 def get(self):
3454 """Returns the spinbox's string"""
3455 return self.tk.call(self._w, 'get')
Raymond Hettingerff41c482003-04-06 09:01:11 +00003456
Martin v. Löwis2ec36272002-10-13 10:22:08 +00003457 def icursor(self, index):
3458 """Alter the position of the insertion cursor.
Raymond Hettingerff41c482003-04-06 09:01:11 +00003459
3460 The insertion cursor will be displayed just before
Martin v. Löwis2ec36272002-10-13 10:22:08 +00003461 the character given by index. Returns an empty string
3462 """
3463 return self.tk.call(self._w, 'icursor', index)
Raymond Hettingerff41c482003-04-06 09:01:11 +00003464
Martin v. Löwis2ec36272002-10-13 10:22:08 +00003465 def identify(self, x, y):
Raymond Hettingerff41c482003-04-06 09:01:11 +00003466 """Returns the name of the widget at position x, y
3467
Martin v. Löwis2ec36272002-10-13 10:22:08 +00003468 Return value is one of: none, buttondown, buttonup, entry
3469 """
3470 return self.tk.call(self._w, 'identify', x, y)
Raymond Hettingerff41c482003-04-06 09:01:11 +00003471
Martin v. Löwis2ec36272002-10-13 10:22:08 +00003472 def index(self, index):
3473 """Returns the numerical index corresponding to index
3474 """
3475 return self.tk.call(self._w, 'index', index)
Raymond Hettingerff41c482003-04-06 09:01:11 +00003476
Martin v. Löwis2ec36272002-10-13 10:22:08 +00003477 def insert(self, index, s):
Raymond Hettingerff41c482003-04-06 09:01:11 +00003478 """Insert string s at index
3479
Martin v. Löwis2ec36272002-10-13 10:22:08 +00003480 Returns an empty string.
3481 """
3482 return self.tk.call(self._w, 'insert', index, s)
Raymond Hettingerff41c482003-04-06 09:01:11 +00003483
Martin v. Löwis2ec36272002-10-13 10:22:08 +00003484 def invoke(self, element):
3485 """Causes the specified element to be invoked
Raymond Hettingerff41c482003-04-06 09:01:11 +00003486
Martin v. Löwis2ec36272002-10-13 10:22:08 +00003487 The element could be buttondown or buttonup
3488 triggering the action associated with it.
3489 """
3490 return self.tk.call(self._w, 'invoke', element)
Raymond Hettingerff41c482003-04-06 09:01:11 +00003491
Martin v. Löwis2ec36272002-10-13 10:22:08 +00003492 def scan(self, *args):
3493 """Internal function."""
3494 return self._getints(
3495 self.tk.call((self._w, 'scan') + args)) or ()
Raymond Hettingerff41c482003-04-06 09:01:11 +00003496
Martin v. Löwis2ec36272002-10-13 10:22:08 +00003497 def scan_mark(self, x):
Raymond Hettingerff41c482003-04-06 09:01:11 +00003498 """Records x and the current view in the spinbox window;
3499
3500 used in conjunction with later scan dragto commands.
3501 Typically this command is associated with a mouse button
Martin v. Löwis2ec36272002-10-13 10:22:08 +00003502 press in the widget. It returns an empty string.
3503 """
3504 return self.scan("mark", x)
Raymond Hettingerff41c482003-04-06 09:01:11 +00003505
Martin v. Löwis2ec36272002-10-13 10:22:08 +00003506 def scan_dragto(self, x):
Raymond Hettingerff41c482003-04-06 09:01:11 +00003507 """Compute the difference between the given x argument
Martin v. Löwis2ec36272002-10-13 10:22:08 +00003508 and the x argument to the last scan mark command
Raymond Hettingerff41c482003-04-06 09:01:11 +00003509
3510 It then adjusts the view left or right by 10 times the
3511 difference in x-coordinates. This command is typically
3512 associated with mouse motion events in the widget, to
Martin v. Löwis2ec36272002-10-13 10:22:08 +00003513 produce the effect of dragging the spinbox at high speed
3514 through the window. The return value is an empty string.
3515 """
3516 return self.scan("dragto", x)
Raymond Hettingerff41c482003-04-06 09:01:11 +00003517
Martin v. Löwis2ec36272002-10-13 10:22:08 +00003518 def selection(self, *args):
3519 """Internal function."""
3520 return self._getints(
3521 self.tk.call((self._w, 'selection') + args)) or ()
Raymond Hettingerff41c482003-04-06 09:01:11 +00003522
Martin v. Löwis2ec36272002-10-13 10:22:08 +00003523 def selection_adjust(self, index):
3524 """Locate the end of the selection nearest to the character
Raymond Hettingerff41c482003-04-06 09:01:11 +00003525 given by index,
3526
3527 Then adjust that end of the selection to be at index
3528 (i.e including but not going beyond index). The other
Martin v. Löwis2ec36272002-10-13 10:22:08 +00003529 end of the selection is made the anchor point for future
Raymond Hettingerff41c482003-04-06 09:01:11 +00003530 select to commands. If the selection isn't currently in
3531 the spinbox, then a new selection is created to include
3532 the characters between index and the most recent selection
Martin v. Löwis2ec36272002-10-13 10:22:08 +00003533 anchor point, inclusive. Returns an empty string.
3534 """
3535 return self.selection("adjust", index)
Raymond Hettingerff41c482003-04-06 09:01:11 +00003536
Martin v. Löwis2ec36272002-10-13 10:22:08 +00003537 def selection_clear(self):
Raymond Hettingerff41c482003-04-06 09:01:11 +00003538 """Clear the selection
3539
3540 If the selection isn't in this widget then the
Martin v. Löwis2ec36272002-10-13 10:22:08 +00003541 command has no effect. Returns an empty string.
3542 """
3543 return self.selection("clear")
Raymond Hettingerff41c482003-04-06 09:01:11 +00003544
Martin v. Löwis2ec36272002-10-13 10:22:08 +00003545 def selection_element(self, element=None):
Raymond Hettingerff41c482003-04-06 09:01:11 +00003546 """Sets or gets the currently selected element.
3547
3548 If a spinbutton element is specified, it will be
Martin v. Löwis2ec36272002-10-13 10:22:08 +00003549 displayed depressed
3550 """
3551 return self.selection("element", element)
3552
3553###########################################################################
3554
3555class LabelFrame(Widget):
3556 """labelframe widget."""
3557 def __init__(self, master=None, cnf={}, **kw):
3558 """Construct a labelframe widget with the parent MASTER.
Raymond Hettingerff41c482003-04-06 09:01:11 +00003559
Martin v. Löwis2ec36272002-10-13 10:22:08 +00003560 STANDARD OPTIONS
Raymond Hettingerff41c482003-04-06 09:01:11 +00003561
3562 borderwidth, cursor, font, foreground,
3563 highlightbackground, highlightcolor,
3564 highlightthickness, padx, pady, relief,
Martin v. Löwis2ec36272002-10-13 10:22:08 +00003565 takefocus, text
Raymond Hettingerff41c482003-04-06 09:01:11 +00003566
Martin v. Löwis2ec36272002-10-13 10:22:08 +00003567 WIDGET-SPECIFIC OPTIONS
Raymond Hettingerff41c482003-04-06 09:01:11 +00003568
3569 background, class, colormap, container,
3570 height, labelanchor, labelwidget,
Martin v. Löwis2ec36272002-10-13 10:22:08 +00003571 visual, width
3572 """
3573 Widget.__init__(self, master, 'labelframe', cnf, kw)
Raymond Hettingerff41c482003-04-06 09:01:11 +00003574
Martin v. Löwis2ec36272002-10-13 10:22:08 +00003575########################################################################
3576
3577class PanedWindow(Widget):
3578 """panedwindow widget."""
3579 def __init__(self, master=None, cnf={}, **kw):
3580 """Construct a panedwindow widget with the parent MASTER.
Raymond Hettingerff41c482003-04-06 09:01:11 +00003581
Martin v. Löwis2ec36272002-10-13 10:22:08 +00003582 STANDARD OPTIONS
Raymond Hettingerff41c482003-04-06 09:01:11 +00003583
Martin v. Löwis2ec36272002-10-13 10:22:08 +00003584 background, borderwidth, cursor, height,
3585 orient, relief, width
Raymond Hettingerff41c482003-04-06 09:01:11 +00003586
Martin v. Löwis2ec36272002-10-13 10:22:08 +00003587 WIDGET-SPECIFIC OPTIONS
Raymond Hettingerff41c482003-04-06 09:01:11 +00003588
3589 handlepad, handlesize, opaqueresize,
3590 sashcursor, sashpad, sashrelief,
Martin v. Löwis2ec36272002-10-13 10:22:08 +00003591 sashwidth, showhandle,
3592 """
3593 Widget.__init__(self, master, 'panedwindow', cnf, kw)
3594
3595 def add(self, child, **kw):
Raymond Hettingerff41c482003-04-06 09:01:11 +00003596 """Add a child widget to the panedwindow in a new pane.
3597
3598 The child argument is the name of the child widget
3599 followed by pairs of arguments that specify how to
Guilherme Polo86425562009-05-31 21:35:23 +00003600 manage the windows. The possible options and values
3601 are the ones accepted by the paneconfigure method.
Martin v. Löwis2ec36272002-10-13 10:22:08 +00003602 """
3603 self.tk.call((self._w, 'add', child) + self._options(kw))
Raymond Hettingerff41c482003-04-06 09:01:11 +00003604
Martin v. Löwis2ec36272002-10-13 10:22:08 +00003605 def remove(self, child):
3606 """Remove the pane containing child from the panedwindow
Raymond Hettingerff41c482003-04-06 09:01:11 +00003607
Martin v. Löwis2ec36272002-10-13 10:22:08 +00003608 All geometry management options for child will be forgotten.
3609 """
3610 self.tk.call(self._w, 'forget', child)
3611 forget=remove
Raymond Hettingerff41c482003-04-06 09:01:11 +00003612
Martin v. Löwis2ec36272002-10-13 10:22:08 +00003613 def identify(self, x, y):
3614 """Identify the panedwindow component at point x, y
Raymond Hettingerff41c482003-04-06 09:01:11 +00003615
3616 If the point is over a sash or a sash handle, the result
Martin v. Löwis2ec36272002-10-13 10:22:08 +00003617 is a two element list containing the index of the sash or
Raymond Hettingerff41c482003-04-06 09:01:11 +00003618 handle, and a word indicating whether it is over a sash
3619 or a handle, such as {0 sash} or {2 handle}. If the point
3620 is over any other part of the panedwindow, the result is
Martin v. Löwis2ec36272002-10-13 10:22:08 +00003621 an empty list.
3622 """
3623 return self.tk.call(self._w, 'identify', x, y)
Raymond Hettingerff41c482003-04-06 09:01:11 +00003624
Martin v. Löwis2ec36272002-10-13 10:22:08 +00003625 def proxy(self, *args):
3626 """Internal function."""
3627 return self._getints(
Raymond Hettingerff41c482003-04-06 09:01:11 +00003628 self.tk.call((self._w, 'proxy') + args)) or ()
3629
Martin v. Löwis2ec36272002-10-13 10:22:08 +00003630 def proxy_coord(self):
3631 """Return the x and y pair of the most recent proxy location
3632 """
3633 return self.proxy("coord")
Raymond Hettingerff41c482003-04-06 09:01:11 +00003634
Martin v. Löwis2ec36272002-10-13 10:22:08 +00003635 def proxy_forget(self):
3636 """Remove the proxy from the display.
3637 """
3638 return self.proxy("forget")
Raymond Hettingerff41c482003-04-06 09:01:11 +00003639
Martin v. Löwis2ec36272002-10-13 10:22:08 +00003640 def proxy_place(self, x, y):
Raymond Hettingerff41c482003-04-06 09:01:11 +00003641 """Place the proxy at the given x and y coordinates.
Martin v. Löwis2ec36272002-10-13 10:22:08 +00003642 """
3643 return self.proxy("place", x, y)
Raymond Hettingerff41c482003-04-06 09:01:11 +00003644
Martin v. Löwis2ec36272002-10-13 10:22:08 +00003645 def sash(self, *args):
3646 """Internal function."""
3647 return self._getints(
3648 self.tk.call((self._w, 'sash') + args)) or ()
Raymond Hettingerff41c482003-04-06 09:01:11 +00003649
Martin v. Löwis2ec36272002-10-13 10:22:08 +00003650 def sash_coord(self, index):
Raymond Hettingerff41c482003-04-06 09:01:11 +00003651 """Return the current x and y pair for the sash given by index.
3652
3653 Index must be an integer between 0 and 1 less than the
3654 number of panes in the panedwindow. The coordinates given are
3655 those of the top left corner of the region containing the sash.
3656 pathName sash dragto index x y This command computes the
3657 difference between the given coordinates and the coordinates
3658 given to the last sash coord command for the given sash. It then
3659 moves that sash the computed difference. The return value is the
Martin v. Löwis2ec36272002-10-13 10:22:08 +00003660 empty string.
3661 """
3662 return self.sash("coord", index)
Raymond Hettingerff41c482003-04-06 09:01:11 +00003663
Martin v. Löwis2ec36272002-10-13 10:22:08 +00003664 def sash_mark(self, index):
Raymond Hettingerff41c482003-04-06 09:01:11 +00003665 """Records x and y for the sash given by index;
3666
Martin v. Löwis2ec36272002-10-13 10:22:08 +00003667 Used in conjunction with later dragto commands to move the sash.
3668 """
3669 return self.sash("mark", index)
Raymond Hettingerff41c482003-04-06 09:01:11 +00003670
Martin v. Löwis2ec36272002-10-13 10:22:08 +00003671 def sash_place(self, index, x, y):
3672 """Place the sash given by index at the given coordinates
3673 """
3674 return self.sash("place", index, x, y)
Raymond Hettingerff41c482003-04-06 09:01:11 +00003675
Martin v. Löwis2ec36272002-10-13 10:22:08 +00003676 def panecget(self, child, option):
Raymond Hettingerff41c482003-04-06 09:01:11 +00003677 """Query a management option for window.
3678
Martin v. Löwis2ec36272002-10-13 10:22:08 +00003679 Option may be any value allowed by the paneconfigure subcommand
3680 """
3681 return self.tk.call(
3682 (self._w, 'panecget') + (child, '-'+option))
Raymond Hettingerff41c482003-04-06 09:01:11 +00003683
Martin v. Löwis2ec36272002-10-13 10:22:08 +00003684 def paneconfigure(self, tagOrId, cnf=None, **kw):
Raymond Hettingerff41c482003-04-06 09:01:11 +00003685 """Query or modify the management options for window.
3686
Martin v. Löwis2ec36272002-10-13 10:22:08 +00003687 If no option is specified, returns a list describing all
Raymond Hettingerff41c482003-04-06 09:01:11 +00003688 of the available options for pathName. If option is
3689 specified with no value, then the command returns a list
3690 describing the one named option (this list will be identical
3691 to the corresponding sublist of the value returned if no
3692 option is specified). If one or more option-value pairs are
3693 specified, then the command modifies the given widget
3694 option(s) to have the given value(s); in this case the
3695 command returns an empty string. The following options
Martin v. Löwis2ec36272002-10-13 10:22:08 +00003696 are supported:
Raymond Hettingerff41c482003-04-06 09:01:11 +00003697
Martin v. Löwis2ec36272002-10-13 10:22:08 +00003698 after window
Raymond Hettingerff41c482003-04-06 09:01:11 +00003699 Insert the window after the window specified. window
Martin v. Löwis2ec36272002-10-13 10:22:08 +00003700 should be the name of a window already managed by pathName.
3701 before window
Raymond Hettingerff41c482003-04-06 09:01:11 +00003702 Insert the window before the window specified. window
Martin v. Löwis2ec36272002-10-13 10:22:08 +00003703 should be the name of a window already managed by pathName.
3704 height size
Raymond Hettingerff41c482003-04-06 09:01:11 +00003705 Specify a height for the window. The height will be the
3706 outer dimension of the window including its border, if
3707 any. If size is an empty string, or if -height is not
3708 specified, then the height requested internally by the
3709 window will be used initially; the height may later be
3710 adjusted by the movement of sashes in the panedwindow.
Martin v. Löwis2ec36272002-10-13 10:22:08 +00003711 Size may be any value accepted by Tk_GetPixels.
3712 minsize n
Raymond Hettingerff41c482003-04-06 09:01:11 +00003713 Specifies that the size of the window cannot be made
3714 less than n. This constraint only affects the size of
3715 the widget in the paned dimension -- the x dimension
3716 for horizontal panedwindows, the y dimension for
3717 vertical panedwindows. May be any value accepted by
Martin v. Löwis2ec36272002-10-13 10:22:08 +00003718 Tk_GetPixels.
3719 padx n
Raymond Hettingerff41c482003-04-06 09:01:11 +00003720 Specifies a non-negative value indicating how much
3721 extra space to leave on each side of the window in
3722 the X-direction. The value may have any of the forms
Martin v. Löwis2ec36272002-10-13 10:22:08 +00003723 accepted by Tk_GetPixels.
3724 pady n
3725 Specifies a non-negative value indicating how much
Raymond Hettingerff41c482003-04-06 09:01:11 +00003726 extra space to leave on each side of the window in
3727 the Y-direction. The value may have any of the forms
Martin v. Löwis2ec36272002-10-13 10:22:08 +00003728 accepted by Tk_GetPixels.
3729 sticky style
Raymond Hettingerff41c482003-04-06 09:01:11 +00003730 If a window's pane is larger than the requested
3731 dimensions of the window, this option may be used
3732 to position (or stretch) the window within its pane.
3733 Style is a string that contains zero or more of the
3734 characters n, s, e or w. The string can optionally
3735 contains spaces or commas, but they are ignored. Each
3736 letter refers to a side (north, south, east, or west)
3737 that the window will "stick" to. If both n and s
3738 (or e and w) are specified, the window will be
3739 stretched to fill the entire height (or width) of
Martin v. Löwis2ec36272002-10-13 10:22:08 +00003740 its cavity.
3741 width size
Raymond Hettingerff41c482003-04-06 09:01:11 +00003742 Specify a width for the window. The width will be
3743 the outer dimension of the window including its
3744 border, if any. If size is an empty string, or
Martin v. Löwis2ec36272002-10-13 10:22:08 +00003745 if -width is not specified, then the width requested
Raymond Hettingerff41c482003-04-06 09:01:11 +00003746 internally by the window will be used initially; the
3747 width may later be adjusted by the movement of sashes
3748 in the panedwindow. Size may be any value accepted by
Martin v. Löwis2ec36272002-10-13 10:22:08 +00003749 Tk_GetPixels.
Raymond Hettingerff41c482003-04-06 09:01:11 +00003750
Martin v. Löwis2ec36272002-10-13 10:22:08 +00003751 """
3752 if cnf is None and not kw:
3753 cnf = {}
3754 for x in self.tk.split(
3755 self.tk.call(self._w,
3756 'paneconfigure', tagOrId)):
3757 cnf[x[0][1:]] = (x[0][1:],) + x[1:]
3758 return cnf
Guido van Rossum13257902007-06-07 23:15:56 +00003759 if isinstance(cnf, str) and not kw:
Martin v. Löwis2ec36272002-10-13 10:22:08 +00003760 x = self.tk.split(self.tk.call(
3761 self._w, 'paneconfigure', tagOrId, '-'+cnf))
3762 return (x[0][1:],) + x[1:]
3763 self.tk.call((self._w, 'paneconfigure', tagOrId) +
3764 self._options(cnf, kw))
3765 paneconfig = paneconfigure
3766
3767 def panes(self):
3768 """Returns an ordered list of the child panes."""
3769 return self.tk.call(self._w, 'panes')
3770
Guido van Rossumaec5dc91994-06-27 07:55:12 +00003771######################################################################
3772# Extensions:
3773
3774class Studbutton(Button):
Fredrik Lundh06d28152000-08-09 18:03:12 +00003775 def __init__(self, master=None, cnf={}, **kw):
3776 Widget.__init__(self, master, 'studbutton', cnf, kw)
3777 self.bind('<Any-Enter>', self.tkButtonEnter)
3778 self.bind('<Any-Leave>', self.tkButtonLeave)
3779 self.bind('<1>', self.tkButtonDown)
3780 self.bind('<ButtonRelease-1>', self.tkButtonUp)
Guido van Rossumaec5dc91994-06-27 07:55:12 +00003781
3782class Tributton(Button):
Fredrik Lundh06d28152000-08-09 18:03:12 +00003783 def __init__(self, master=None, cnf={}, **kw):
3784 Widget.__init__(self, master, 'tributton', cnf, kw)
3785 self.bind('<Any-Enter>', self.tkButtonEnter)
3786 self.bind('<Any-Leave>', self.tkButtonLeave)
3787 self.bind('<1>', self.tkButtonDown)
3788 self.bind('<ButtonRelease-1>', self.tkButtonUp)
3789 self['fg'] = self['bg']
3790 self['activebackground'] = self['bg']
Guido van Rossum37dcab11996-05-16 16:00:19 +00003791
Guido van Rossumc417ef81996-08-21 23:38:59 +00003792######################################################################
3793# Test:
3794
3795def _test():
Fredrik Lundh06d28152000-08-09 18:03:12 +00003796 root = Tk()
3797 text = "This is Tcl/Tk version %s" % TclVersion
3798 if TclVersion >= 8.1:
Walter Dörwald5de48bd2007-06-11 21:38:39 +00003799 text += "\nThis should be a cedilla: \xe7"
Fredrik Lundh06d28152000-08-09 18:03:12 +00003800 label = Label(root, text=text)
3801 label.pack()
3802 test = Button(root, text="Click me!",
3803 command=lambda root=root: root.test.configure(
3804 text="[%s]" % root.test['text']))
3805 test.pack()
3806 root.test = test
3807 quit = Button(root, text="QUIT", command=root.destroy)
3808 quit.pack()
3809 # The following three commands are needed so the window pops
3810 # up on top on Windows...
3811 root.iconify()
3812 root.update()
3813 root.deiconify()
3814 root.mainloop()
Guido van Rossumc417ef81996-08-21 23:38:59 +00003815
3816if __name__ == '__main__':
Fredrik Lundh06d28152000-08-09 18:03:12 +00003817 _test()