blob: f61978640517f10163000b6422c45f4279ba76db [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 *
Serhiy Storchakab1396522013-01-15 17:56:08 +020043import re
Guido van Rossum18468821994-06-20 07:49:28 +000044
Andrew Svetlova966c6f2012-03-21 23:52:59 +020045
Martin v. Löwis8c8aa5d2002-11-26 21:39:48 +000046wantobjects = 1
Martin v. Löwisffad6332002-11-26 09:28:05 +000047
Eric S. Raymondfc170b12001-02-09 11:51:27 +000048TkVersion = float(_tkinter.TK_VERSION)
49TclVersion = float(_tkinter.TCL_VERSION)
Guido van Rossum18468821994-06-20 07:49:28 +000050
Guido van Rossumd6615ab1997-08-05 02:35:01 +000051READABLE = _tkinter.READABLE
52WRITABLE = _tkinter.WRITABLE
53EXCEPTION = _tkinter.EXCEPTION
Guido van Rossumf53c86c1997-08-14 14:15:54 +000054
Fredrik Lundh06d28152000-08-09 18:03:12 +000055
Serhiy Storchakab1396522013-01-15 17:56:08 +020056_magic_re = re.compile(r'([\\{}])')
57_space_re = re.compile(r'([\s])', re.ASCII)
58
59def _join(value):
60 """Internal function."""
61 return ' '.join(map(_stringify, value))
62
63def _stringify(value):
64 """Internal function."""
65 if isinstance(value, (list, tuple)):
66 if len(value) == 1:
67 value = _stringify(value[0])
68 if value[0] == '{':
69 value = '{%s}' % value
70 else:
71 value = '{%s}' % _join(value)
72 else:
73 value = str(value)
74 if not value:
75 value = '{}'
76 elif _magic_re.search(value):
77 # add '\' before special characters and spaces
78 value = _magic_re.sub(r'\\\1', value)
79 value = _space_re.sub(r'\\\1', value)
80 elif value[0] == '"' or _space_re.search(value):
81 value = '{%s}' % value
82 return value
83
Guido van Rossum13257902007-06-07 23:15:56 +000084def _flatten(seq):
Fredrik Lundh06d28152000-08-09 18:03:12 +000085 """Internal function."""
86 res = ()
Guido van Rossum13257902007-06-07 23:15:56 +000087 for item in seq:
88 if isinstance(item, (tuple, list)):
Fredrik Lundh06d28152000-08-09 18:03:12 +000089 res = res + _flatten(item)
90 elif item is not None:
91 res = res + (item,)
92 return res
Guido van Rossum2dcf5291994-07-06 09:23:20 +000093
Andrew M. Kuchlinge475e702000-06-18 18:45:50 +000094try: _flatten = _tkinter._flatten
95except AttributeError: pass
96
Guido van Rossum2dcf5291994-07-06 09:23:20 +000097def _cnfmerge(cnfs):
Fredrik Lundh06d28152000-08-09 18:03:12 +000098 """Internal function."""
Guido van Rossum13257902007-06-07 23:15:56 +000099 if isinstance(cnfs, dict):
Fredrik Lundh06d28152000-08-09 18:03:12 +0000100 return cnfs
Guido van Rossum13257902007-06-07 23:15:56 +0000101 elif isinstance(cnfs, (type(None), str)):
Fredrik Lundh06d28152000-08-09 18:03:12 +0000102 return cnfs
103 else:
104 cnf = {}
105 for c in _flatten(cnfs):
106 try:
107 cnf.update(c)
Guido van Rossumb940e112007-01-10 16:19:56 +0000108 except (AttributeError, TypeError) as msg:
Guido van Rossumbe19ed72007-02-09 05:37:30 +0000109 print("_cnfmerge: fallback due to:", msg)
Fredrik Lundh06d28152000-08-09 18:03:12 +0000110 for k, v in c.items():
111 cnf[k] = v
112 return cnf
Guido van Rossum2dcf5291994-07-06 09:23:20 +0000113
Andrew M. Kuchlinge475e702000-06-18 18:45:50 +0000114try: _cnfmerge = _tkinter._cnfmerge
115except AttributeError: pass
116
Guido van Rossum2dcf5291994-07-06 09:23:20 +0000117class Event:
Fredrik Lundh06d28152000-08-09 18:03:12 +0000118 """Container for the properties of an event.
Guido van Rossum5917ecb2000-06-29 16:30:50 +0000119
Fredrik Lundh06d28152000-08-09 18:03:12 +0000120 Instances of this type are generated if one of the following events occurs:
Guido van Rossum5917ecb2000-06-29 16:30:50 +0000121
Fredrik Lundh06d28152000-08-09 18:03:12 +0000122 KeyPress, KeyRelease - for keyboard events
123 ButtonPress, ButtonRelease, Motion, Enter, Leave, MouseWheel - for mouse events
124 Visibility, Unmap, Map, Expose, FocusIn, FocusOut, Circulate,
125 Colormap, Gravity, Reparent, Property, Destroy, Activate,
126 Deactivate - for window events.
127
128 If a callback function for one of these events is registered
129 using bind, bind_all, bind_class, or tag_bind, the callback is
130 called with an Event as first argument. It will have the
131 following attributes (in braces are the event types for which
132 the attribute is valid):
133
Guido van Rossum5917ecb2000-06-29 16:30:50 +0000134 serial - serial number of event
Fredrik Lundh06d28152000-08-09 18:03:12 +0000135 num - mouse button pressed (ButtonPress, ButtonRelease)
136 focus - whether the window has the focus (Enter, Leave)
137 height - height of the exposed window (Configure, Expose)
138 width - width of the exposed window (Configure, Expose)
139 keycode - keycode of the pressed key (KeyPress, KeyRelease)
140 state - state of the event as a number (ButtonPress, ButtonRelease,
141 Enter, KeyPress, KeyRelease,
142 Leave, Motion)
143 state - state as a string (Visibility)
144 time - when the event occurred
145 x - x-position of the mouse
146 y - y-position of the mouse
147 x_root - x-position of the mouse on the screen
148 (ButtonPress, ButtonRelease, KeyPress, KeyRelease, Motion)
149 y_root - y-position of the mouse on the screen
150 (ButtonPress, ButtonRelease, KeyPress, KeyRelease, Motion)
151 char - pressed character (KeyPress, KeyRelease)
152 send_event - see X/Windows documentation
Walter Dörwald966c2642005-11-09 17:12:43 +0000153 keysym - keysym of the event as a string (KeyPress, KeyRelease)
Fredrik Lundh06d28152000-08-09 18:03:12 +0000154 keysym_num - keysym of the event as a number (KeyPress, KeyRelease)
155 type - type of the event as a number
156 widget - widget in which the event occurred
157 delta - delta of wheel movement (MouseWheel)
158 """
159 pass
Guido van Rossum2dcf5291994-07-06 09:23:20 +0000160
Guido van Rossumc4570481998-03-20 20:45:49 +0000161_support_default_root = 1
Guido van Rossumaec5dc91994-06-27 07:55:12 +0000162_default_root = None
163
Guido van Rossumc4570481998-03-20 20:45:49 +0000164def NoDefaultRoot():
Fredrik Lundh06d28152000-08-09 18:03:12 +0000165 """Inhibit setting of default root window.
Guido van Rossum5917ecb2000-06-29 16:30:50 +0000166
Fredrik Lundh06d28152000-08-09 18:03:12 +0000167 Call this function to inhibit that the first instance of
168 Tk is used for windows without an explicit parent window.
169 """
170 global _support_default_root
171 _support_default_root = 0
172 global _default_root
173 _default_root = None
174 del _default_root
Guido van Rossumc4570481998-03-20 20:45:49 +0000175
Guido van Rossum45853db1994-06-20 12:19:19 +0000176def _tkerror(err):
Fredrik Lundh06d28152000-08-09 18:03:12 +0000177 """Internal function."""
178 pass
Guido van Rossum18468821994-06-20 07:49:28 +0000179
Andrew Svetlov806bfad2012-12-10 00:02:31 +0200180def _exit(code=0):
Andrew Svetlov737fb892012-12-18 21:14:22 +0200181 """Internal function. Calling it will raise the exception SystemExit."""
Andrew Svetlov806bfad2012-12-10 00:02:31 +0200182 try:
183 code = int(code)
184 except ValueError:
185 pass
Collin Winterce36ad82007-08-30 01:19:48 +0000186 raise SystemExit(code)
Guido van Rossum97aeca11994-07-07 13:12:12 +0000187
Guido van Rossumaec5dc91994-06-27 07:55:12 +0000188_varnum = 0
189class Variable:
Guido van Rossum2cd0a652003-04-16 20:10:03 +0000190 """Class to define value holders for e.g. buttons.
191
192 Subclasses StringVar, IntVar, DoubleVar, BooleanVar are specializations
193 that constrain the type of the value returned from get()."""
Fredrik Lundh06d28152000-08-09 18:03:12 +0000194 _default = ""
Martin v. Löwis2b695a42012-03-12 17:47:35 -0700195 _tk = None
Thomas Wouters0e3f5912006-08-11 14:57:12 +0000196 def __init__(self, master=None, value=None, name=None):
197 """Construct a variable
198
199 MASTER can be given as master widget.
200 VALUE is an optional value (defaults to "")
201 NAME is an optional Tcl name (defaults to PY_VARnum).
202
203 If NAME matches an existing variable and VALUE is omitted
204 then the existing value is retained.
Fredrik Lundh06d28152000-08-09 18:03:12 +0000205 """
Martin v. Löwis2b695a42012-03-12 17:47:35 -0700206 # check for type of NAME parameter to override weird error message
207 # raised from Modules/_tkinter.c:SetVar like:
208 # TypeError: setvar() takes exactly 3 arguments (2 given)
209 if name is not None and not isinstance(name, str):
210 raise TypeError("name must be a string")
Fredrik Lundh06d28152000-08-09 18:03:12 +0000211 global _varnum
212 if not master:
213 master = _default_root
214 self._master = master
215 self._tk = master.tk
Thomas Wouters0e3f5912006-08-11 14:57:12 +0000216 if name:
217 self._name = name
218 else:
219 self._name = 'PY_VAR' + repr(_varnum)
220 _varnum += 1
Benjamin Peterson2a691a82008-03-31 01:51:45 +0000221 if value is not None:
Martin v. Löwis2b695a42012-03-12 17:47:35 -0700222 self.initialize(value)
Thomas Wouters0e3f5912006-08-11 14:57:12 +0000223 elif not self._tk.call("info", "exists", self._name):
Martin v. Löwis2b695a42012-03-12 17:47:35 -0700224 self.initialize(self._default)
Fredrik Lundh06d28152000-08-09 18:03:12 +0000225 def __del__(self):
226 """Unset the variable in Tcl."""
Martin v. Löwis2b695a42012-03-12 17:47:35 -0700227 if (self._tk is not None and self._tk.call("info", "exists",
228 self._name)):
229 self._tk.globalunsetvar(self._name)
Fredrik Lundh06d28152000-08-09 18:03:12 +0000230 def __str__(self):
231 """Return the name of the variable in Tcl."""
232 return self._name
233 def set(self, value):
234 """Set the variable to VALUE."""
235 return self._tk.globalsetvar(self._name, value)
Martin v. Löwis2b695a42012-03-12 17:47:35 -0700236 initialize = set
Guido van Rossum2cd0a652003-04-16 20:10:03 +0000237 def get(self):
238 """Return value of variable."""
239 return self._tk.globalgetvar(self._name)
Fredrik Lundh06d28152000-08-09 18:03:12 +0000240 def trace_variable(self, mode, callback):
241 """Define a trace callback for the variable.
Guido van Rossum5917ecb2000-06-29 16:30:50 +0000242
Fredrik Lundh06d28152000-08-09 18:03:12 +0000243 MODE is one of "r", "w", "u" for read, write, undefine.
244 CALLBACK must be a function which is called when
245 the variable is read, written or undefined.
Guido van Rossum5917ecb2000-06-29 16:30:50 +0000246
Fredrik Lundh06d28152000-08-09 18:03:12 +0000247 Return the name of the callback.
248 """
249 cbname = self._master._register(callback)
250 self._tk.call("trace", "variable", self._name, mode, cbname)
251 return cbname
252 trace = trace_variable
253 def trace_vdelete(self, mode, cbname):
254 """Delete the trace callback for a variable.
Guido van Rossum5917ecb2000-06-29 16:30:50 +0000255
Fredrik Lundh06d28152000-08-09 18:03:12 +0000256 MODE is one of "r", "w", "u" for read, write, undefine.
257 CBNAME is the name of the callback returned from trace_variable or trace.
258 """
259 self._tk.call("trace", "vdelete", self._name, mode, cbname)
260 self._master.deletecommand(cbname)
261 def trace_vinfo(self):
262 """Return all trace callback information."""
Alexander Belopolsky022f0492010-11-22 19:40:51 +0000263 return [self._tk.split(x) for x in self._tk.splitlist(
264 self._tk.call("trace", "vinfo", self._name))]
Thomas Wouters0e3f5912006-08-11 14:57:12 +0000265 def __eq__(self, other):
266 """Comparison for equality (==).
267
268 Note: if the Variable's master matters to behavior
269 also compare self._master == other._master
270 """
271 return self.__class__.__name__ == other.__class__.__name__ \
272 and self._name == other._name
Guido van Rossumaec5dc91994-06-27 07:55:12 +0000273
274class StringVar(Variable):
Fredrik Lundh06d28152000-08-09 18:03:12 +0000275 """Value holder for strings variables."""
276 _default = ""
Thomas Wouters0e3f5912006-08-11 14:57:12 +0000277 def __init__(self, master=None, value=None, name=None):
Fredrik Lundh06d28152000-08-09 18:03:12 +0000278 """Construct a string variable.
Guido van Rossum5917ecb2000-06-29 16:30:50 +0000279
Thomas Wouters0e3f5912006-08-11 14:57:12 +0000280 MASTER can be given as master widget.
281 VALUE is an optional value (defaults to "")
282 NAME is an optional Tcl name (defaults to PY_VARnum).
283
284 If NAME matches an existing variable and VALUE is omitted
285 then the existing value is retained.
286 """
287 Variable.__init__(self, master, value, name)
Guido van Rossum5917ecb2000-06-29 16:30:50 +0000288
Fredrik Lundh06d28152000-08-09 18:03:12 +0000289 def get(self):
290 """Return value of variable as string."""
Martin v. Löwisbfe175c2003-04-16 19:42:51 +0000291 value = self._tk.globalgetvar(self._name)
Guido van Rossum3172c5d2007-10-16 18:12:55 +0000292 if isinstance(value, str):
Martin v. Löwisbfe175c2003-04-16 19:42:51 +0000293 return value
294 return str(value)
Guido van Rossumaec5dc91994-06-27 07:55:12 +0000295
296class IntVar(Variable):
Fredrik Lundh06d28152000-08-09 18:03:12 +0000297 """Value holder for integer variables."""
298 _default = 0
Thomas Wouters0e3f5912006-08-11 14:57:12 +0000299 def __init__(self, master=None, value=None, name=None):
Fredrik Lundh06d28152000-08-09 18:03:12 +0000300 """Construct an integer variable.
Guido van Rossum5917ecb2000-06-29 16:30:50 +0000301
Thomas Wouters0e3f5912006-08-11 14:57:12 +0000302 MASTER can be given as master widget.
303 VALUE is an optional value (defaults to 0)
304 NAME is an optional Tcl name (defaults to PY_VARnum).
305
306 If NAME matches an existing variable and VALUE is omitted
307 then the existing value is retained.
308 """
309 Variable.__init__(self, master, value, name)
Guido van Rossum5917ecb2000-06-29 16:30:50 +0000310
Fredrik Lundh06d28152000-08-09 18:03:12 +0000311 def get(self):
312 """Return the value of the variable as an integer."""
313 return getint(self._tk.globalgetvar(self._name))
Guido van Rossumaec5dc91994-06-27 07:55:12 +0000314
315class DoubleVar(Variable):
Fredrik Lundh06d28152000-08-09 18:03:12 +0000316 """Value holder for float variables."""
317 _default = 0.0
Thomas Wouters0e3f5912006-08-11 14:57:12 +0000318 def __init__(self, master=None, value=None, name=None):
Fredrik Lundh06d28152000-08-09 18:03:12 +0000319 """Construct a float variable.
Guido van Rossum5917ecb2000-06-29 16:30:50 +0000320
Thomas Wouters0e3f5912006-08-11 14:57:12 +0000321 MASTER can be given as master widget.
322 VALUE is an optional value (defaults to 0.0)
323 NAME is an optional Tcl name (defaults to PY_VARnum).
324
325 If NAME matches an existing variable and VALUE is omitted
326 then the existing value is retained.
327 """
328 Variable.__init__(self, master, value, name)
Fredrik Lundh06d28152000-08-09 18:03:12 +0000329
330 def get(self):
331 """Return the value of the variable as a float."""
332 return getdouble(self._tk.globalgetvar(self._name))
Guido van Rossumaec5dc91994-06-27 07:55:12 +0000333
334class BooleanVar(Variable):
Fredrik Lundh06d28152000-08-09 18:03:12 +0000335 """Value holder for boolean variables."""
Thomas Wouters0e3f5912006-08-11 14:57:12 +0000336 _default = False
337 def __init__(self, master=None, value=None, name=None):
Fredrik Lundh06d28152000-08-09 18:03:12 +0000338 """Construct a boolean variable.
Guido van Rossum5917ecb2000-06-29 16:30:50 +0000339
Thomas Wouters0e3f5912006-08-11 14:57:12 +0000340 MASTER can be given as master widget.
341 VALUE is an optional value (defaults to False)
342 NAME is an optional Tcl name (defaults to PY_VARnum).
343
344 If NAME matches an existing variable and VALUE is omitted
345 then the existing value is retained.
346 """
347 Variable.__init__(self, master, value, name)
Guido van Rossum5917ecb2000-06-29 16:30:50 +0000348
Fredrik Lundh06d28152000-08-09 18:03:12 +0000349 def get(self):
Martin v. Löwisbfe175c2003-04-16 19:42:51 +0000350 """Return the value of the variable as a bool."""
Martin v. Löwis2b695a42012-03-12 17:47:35 -0700351 try:
352 return self._tk.getboolean(self._tk.globalgetvar(self._name))
353 except TclError:
354 raise ValueError("invalid literal for getboolean()")
Guido van Rossumaec5dc91994-06-27 07:55:12 +0000355
Guido van Rossum35f67fb1995-08-04 03:50:29 +0000356def mainloop(n=0):
Fredrik Lundh06d28152000-08-09 18:03:12 +0000357 """Run the main loop of Tcl."""
358 _default_root.tk.mainloop(n)
Guido van Rossum2dcf5291994-07-06 09:23:20 +0000359
Guido van Rossum0132f691998-04-30 17:50:36 +0000360getint = int
Guido van Rossum2dcf5291994-07-06 09:23:20 +0000361
Guido van Rossum0132f691998-04-30 17:50:36 +0000362getdouble = float
Guido van Rossum2dcf5291994-07-06 09:23:20 +0000363
364def getboolean(s):
Fredrik Lundh06d28152000-08-09 18:03:12 +0000365 """Convert true and false to integer values 1 and 0."""
Martin v. Löwis2b695a42012-03-12 17:47:35 -0700366 try:
367 return _default_root.tk.getboolean(s)
368 except TclError:
369 raise ValueError("invalid literal for getboolean()")
Guido van Rossum2dcf5291994-07-06 09:23:20 +0000370
Guido van Rossum368e06b1997-11-07 20:38:49 +0000371# Methods defined on both toplevel and interior widgets
Guido van Rossum18468821994-06-20 07:49:28 +0000372class Misc:
Fredrik Lundh06d28152000-08-09 18:03:12 +0000373 """Internal class.
Guido van Rossum5917ecb2000-06-29 16:30:50 +0000374
Fredrik Lundh06d28152000-08-09 18:03:12 +0000375 Base class which defines methods common for interior widgets."""
Guido van Rossum5917ecb2000-06-29 16:30:50 +0000376
Fredrik Lundh06d28152000-08-09 18:03:12 +0000377 # XXX font command?
378 _tclCommands = None
379 def destroy(self):
380 """Internal function.
Guido van Rossum5917ecb2000-06-29 16:30:50 +0000381
Fredrik Lundh06d28152000-08-09 18:03:12 +0000382 Delete all Tcl commands created for
383 this widget in the Tcl interpreter."""
384 if self._tclCommands is not None:
385 for name in self._tclCommands:
386 #print '- Tkinter: deleted command', name
387 self.tk.deletecommand(name)
388 self._tclCommands = None
389 def deletecommand(self, name):
390 """Internal function.
Guido van Rossum5917ecb2000-06-29 16:30:50 +0000391
Fredrik Lundh06d28152000-08-09 18:03:12 +0000392 Delete the Tcl command provided in NAME."""
393 #print '- Tkinter: deleted command', name
394 self.tk.deletecommand(name)
395 try:
396 self._tclCommands.remove(name)
397 except ValueError:
398 pass
399 def tk_strictMotif(self, boolean=None):
400 """Set Tcl internal variable, whether the look and feel
401 should adhere to Motif.
Guido van Rossum5917ecb2000-06-29 16:30:50 +0000402
Fredrik Lundh06d28152000-08-09 18:03:12 +0000403 A parameter of 1 means adhere to Motif (e.g. no color
404 change if mouse passes over slider).
405 Returns the set value."""
406 return self.tk.getboolean(self.tk.call(
407 'set', 'tk_strictMotif', boolean))
408 def tk_bisque(self):
409 """Change the color scheme to light brown as used in Tk 3.6 and before."""
410 self.tk.call('tk_bisque')
411 def tk_setPalette(self, *args, **kw):
412 """Set a new color scheme for all widget elements.
Guido van Rossum5917ecb2000-06-29 16:30:50 +0000413
Fredrik Lundh06d28152000-08-09 18:03:12 +0000414 A single color as argument will cause that all colors of Tk
415 widget elements are derived from this.
416 Alternatively several keyword parameters and its associated
417 colors can be given. The following keywords are valid:
418 activeBackground, foreground, selectColor,
419 activeForeground, highlightBackground, selectBackground,
420 background, highlightColor, selectForeground,
421 disabledForeground, insertBackground, troughColor."""
422 self.tk.call(('tk_setPalette',)
Serhiy Storchaka4cf4f3a2013-01-02 00:03:58 +0200423 + _flatten(args) + _flatten(list(kw.items())))
Fredrik Lundh06d28152000-08-09 18:03:12 +0000424 def tk_menuBar(self, *args):
425 """Do not use. Needed in Tk 3.6 and earlier."""
426 pass # obsolete since Tk 4.0
427 def wait_variable(self, name='PY_VAR'):
428 """Wait until the variable is modified.
Guido van Rossum5917ecb2000-06-29 16:30:50 +0000429
Fredrik Lundh06d28152000-08-09 18:03:12 +0000430 A parameter of type IntVar, StringVar, DoubleVar or
431 BooleanVar must be given."""
432 self.tk.call('tkwait', 'variable', name)
433 waitvar = wait_variable # XXX b/w compat
434 def wait_window(self, window=None):
435 """Wait until a WIDGET is destroyed.
Guido van Rossum5917ecb2000-06-29 16:30:50 +0000436
Fredrik Lundh06d28152000-08-09 18:03:12 +0000437 If no parameter is given self is used."""
Fred Drake132dce22000-12-12 23:11:42 +0000438 if window is None:
Fredrik Lundh06d28152000-08-09 18:03:12 +0000439 window = self
440 self.tk.call('tkwait', 'window', window._w)
441 def wait_visibility(self, window=None):
442 """Wait until the visibility of a WIDGET changes
443 (e.g. it appears).
Guido van Rossum5917ecb2000-06-29 16:30:50 +0000444
Fredrik Lundh06d28152000-08-09 18:03:12 +0000445 If no parameter is given self is used."""
Fred Drake132dce22000-12-12 23:11:42 +0000446 if window is None:
Fredrik Lundh06d28152000-08-09 18:03:12 +0000447 window = self
448 self.tk.call('tkwait', 'visibility', window._w)
449 def setvar(self, name='PY_VAR', value='1'):
450 """Set Tcl variable NAME to VALUE."""
451 self.tk.setvar(name, value)
452 def getvar(self, name='PY_VAR'):
453 """Return value of Tcl variable NAME."""
454 return self.tk.getvar(name)
455 getint = int
456 getdouble = float
457 def getboolean(self, s):
Neal Norwitz6e5be222003-04-17 13:13:55 +0000458 """Return a boolean value for Tcl boolean values true and false given as parameter."""
Martin v. Löwis2b695a42012-03-12 17:47:35 -0700459 try:
460 return self.tk.getboolean(s)
461 except TclError:
462 raise ValueError("invalid literal for getboolean()")
Fredrik Lundh06d28152000-08-09 18:03:12 +0000463 def focus_set(self):
464 """Direct input focus to this widget.
Guido van Rossum5917ecb2000-06-29 16:30:50 +0000465
Fredrik Lundh06d28152000-08-09 18:03:12 +0000466 If the application currently does not have the focus
467 this widget will get the focus if the application gets
468 the focus through the window manager."""
469 self.tk.call('focus', self._w)
470 focus = focus_set # XXX b/w compat?
471 def focus_force(self):
472 """Direct input focus to this widget even if the
473 application does not have the focus. Use with
474 caution!"""
475 self.tk.call('focus', '-force', self._w)
476 def focus_get(self):
477 """Return the widget which has currently the focus in the
478 application.
Guido van Rossum5917ecb2000-06-29 16:30:50 +0000479
Fredrik Lundh06d28152000-08-09 18:03:12 +0000480 Use focus_displayof to allow working with several
481 displays. Return None if application does not have
482 the focus."""
483 name = self.tk.call('focus')
484 if name == 'none' or not name: return None
485 return self._nametowidget(name)
486 def focus_displayof(self):
487 """Return the widget which has currently the focus on the
488 display where this widget is located.
Guido van Rossum5917ecb2000-06-29 16:30:50 +0000489
Fredrik Lundh06d28152000-08-09 18:03:12 +0000490 Return None if the application does not have the focus."""
491 name = self.tk.call('focus', '-displayof', self._w)
492 if name == 'none' or not name: return None
493 return self._nametowidget(name)
494 def focus_lastfor(self):
495 """Return the widget which would have the focus if top level
496 for this widget gets the focus from the window manager."""
497 name = self.tk.call('focus', '-lastfor', self._w)
498 if name == 'none' or not name: return None
499 return self._nametowidget(name)
500 def tk_focusFollowsMouse(self):
501 """The widget under mouse will get automatically focus. Can not
502 be disabled easily."""
503 self.tk.call('tk_focusFollowsMouse')
504 def tk_focusNext(self):
505 """Return the next widget in the focus order which follows
506 widget which has currently the focus.
Guido van Rossum5917ecb2000-06-29 16:30:50 +0000507
Fredrik Lundh06d28152000-08-09 18:03:12 +0000508 The focus order first goes to the next child, then to
509 the children of the child recursively and then to the
510 next sibling which is higher in the stacking order. A
511 widget is omitted if it has the takefocus resource set
512 to 0."""
513 name = self.tk.call('tk_focusNext', self._w)
514 if not name: return None
515 return self._nametowidget(name)
516 def tk_focusPrev(self):
517 """Return previous widget in the focus order. See tk_focusNext for details."""
518 name = self.tk.call('tk_focusPrev', self._w)
519 if not name: return None
520 return self._nametowidget(name)
521 def after(self, ms, func=None, *args):
522 """Call function once after given time.
Guido van Rossum5917ecb2000-06-29 16:30:50 +0000523
Fredrik Lundh06d28152000-08-09 18:03:12 +0000524 MS specifies the time in milliseconds. FUNC gives the
525 function which shall be called. Additional parameters
526 are given as parameters to the function call. Return
527 identifier to cancel scheduling with after_cancel."""
528 if not func:
529 # I'd rather use time.sleep(ms*0.001)
530 self.tk.call('after', ms)
531 else:
Thomas Wouters49fd7fa2006-04-21 10:40:58 +0000532 def callit():
Fredrik Lundh06d28152000-08-09 18:03:12 +0000533 try:
Raymond Hettingerff41c482003-04-06 09:01:11 +0000534 func(*args)
Fredrik Lundh06d28152000-08-09 18:03:12 +0000535 finally:
536 try:
Thomas Wouters49fd7fa2006-04-21 10:40:58 +0000537 self.deletecommand(name)
Fredrik Lundh06d28152000-08-09 18:03:12 +0000538 except TclError:
539 pass
540 name = self._register(callit)
Fredrik Lundh06d28152000-08-09 18:03:12 +0000541 return self.tk.call('after', ms, name)
542 def after_idle(self, func, *args):
543 """Call FUNC once if the Tcl main loop has no event to
544 process.
Guido van Rossum5917ecb2000-06-29 16:30:50 +0000545
Fredrik Lundh06d28152000-08-09 18:03:12 +0000546 Return an identifier to cancel the scheduling with
547 after_cancel."""
Raymond Hettingerff41c482003-04-06 09:01:11 +0000548 return self.after('idle', func, *args)
Fredrik Lundh06d28152000-08-09 18:03:12 +0000549 def after_cancel(self, id):
550 """Cancel scheduling of function identified with ID.
Guido van Rossum5917ecb2000-06-29 16:30:50 +0000551
Fredrik Lundh06d28152000-08-09 18:03:12 +0000552 Identifier returned by after or after_idle must be
553 given as first parameter."""
Martin v. Löwis0f9e5252003-06-07 19:52:38 +0000554 try:
Neal Norwitz3c0f2c92003-07-01 21:12:47 +0000555 data = self.tk.call('after', 'info', id)
556 # In Tk 8.3, splitlist returns: (script, type)
557 # In Tk 8.4, splitlist may return (script, type) or (script,)
558 script = self.tk.splitlist(data)[0]
Martin v. Löwis0f9e5252003-06-07 19:52:38 +0000559 self.deletecommand(script)
560 except TclError:
561 pass
Fredrik Lundh06d28152000-08-09 18:03:12 +0000562 self.tk.call('after', 'cancel', id)
563 def bell(self, displayof=0):
564 """Ring a display's bell."""
565 self.tk.call(('bell',) + self._displayof(displayof))
Thomas Wouters49fd7fa2006-04-21 10:40:58 +0000566
Fredrik Lundh06d28152000-08-09 18:03:12 +0000567 # Clipboard handling:
Thomas Wouters49fd7fa2006-04-21 10:40:58 +0000568 def clipboard_get(self, **kw):
569 """Retrieve data from the clipboard on window's display.
570
571 The window keyword defaults to the root window of the Tkinter
572 application.
573
574 The type keyword specifies the form in which the data is
575 to be returned and should be an atom name such as STRING
Ned Deily4d377d92012-05-15 18:08:11 -0700576 or FILE_NAME. Type defaults to STRING, except on X11, where the default
577 is to try UTF8_STRING and fall back to STRING.
Thomas Wouters49fd7fa2006-04-21 10:40:58 +0000578
579 This command is equivalent to:
580
581 selection_get(CLIPBOARD)
582 """
Ned Deily4d377d92012-05-15 18:08:11 -0700583 if 'type' not in kw and self._windowingsystem == 'x11':
584 try:
585 kw['type'] = 'UTF8_STRING'
586 return self.tk.call(('clipboard', 'get') + self._options(kw))
587 except TclError:
588 del kw['type']
Thomas Wouters49fd7fa2006-04-21 10:40:58 +0000589 return self.tk.call(('clipboard', 'get') + self._options(kw))
590
Fredrik Lundh06d28152000-08-09 18:03:12 +0000591 def clipboard_clear(self, **kw):
592 """Clear the data in the Tk clipboard.
Guido van Rossum5917ecb2000-06-29 16:30:50 +0000593
Fredrik Lundh06d28152000-08-09 18:03:12 +0000594 A widget specified for the optional displayof keyword
595 argument specifies the target display."""
Guido van Rossume014a132006-08-19 16:53:45 +0000596 if 'displayof' not in kw: kw['displayof'] = self._w
Fredrik Lundh06d28152000-08-09 18:03:12 +0000597 self.tk.call(('clipboard', 'clear') + self._options(kw))
598 def clipboard_append(self, string, **kw):
599 """Append STRING to the Tk clipboard.
Guido van Rossum5917ecb2000-06-29 16:30:50 +0000600
Fredrik Lundh06d28152000-08-09 18:03:12 +0000601 A widget specified at the optional displayof keyword
602 argument specifies the target display. The clipboard
603 can be retrieved with selection_get."""
Guido van Rossume014a132006-08-19 16:53:45 +0000604 if 'displayof' not in kw: kw['displayof'] = self._w
Fredrik Lundh06d28152000-08-09 18:03:12 +0000605 self.tk.call(('clipboard', 'append') + self._options(kw)
606 + ('--', string))
607 # XXX grab current w/o window argument
608 def grab_current(self):
609 """Return widget which has currently the grab in this application
610 or None."""
611 name = self.tk.call('grab', 'current', self._w)
612 if not name: return None
613 return self._nametowidget(name)
614 def grab_release(self):
615 """Release grab for this widget if currently set."""
616 self.tk.call('grab', 'release', self._w)
617 def grab_set(self):
618 """Set grab for this widget.
Guido van Rossum5917ecb2000-06-29 16:30:50 +0000619
Fredrik Lundh06d28152000-08-09 18:03:12 +0000620 A grab directs all events to this and descendant
621 widgets in the application."""
622 self.tk.call('grab', 'set', self._w)
623 def grab_set_global(self):
624 """Set global grab for this widget.
Guido van Rossum5917ecb2000-06-29 16:30:50 +0000625
Fredrik Lundh06d28152000-08-09 18:03:12 +0000626 A global grab directs all events to this and
627 descendant widgets on the display. Use with caution -
628 other applications do not get events anymore."""
629 self.tk.call('grab', 'set', '-global', self._w)
630 def grab_status(self):
631 """Return None, "local" or "global" if this widget has
632 no, a local or a global grab."""
633 status = self.tk.call('grab', 'status', self._w)
634 if status == 'none': status = None
635 return status
Fredrik Lundh06d28152000-08-09 18:03:12 +0000636 def option_add(self, pattern, value, priority = None):
637 """Set a VALUE (second parameter) for an option
638 PATTERN (first parameter).
Guido van Rossum5917ecb2000-06-29 16:30:50 +0000639
Fredrik Lundh06d28152000-08-09 18:03:12 +0000640 An optional third parameter gives the numeric priority
641 (defaults to 80)."""
642 self.tk.call('option', 'add', pattern, value, priority)
643 def option_clear(self):
644 """Clear the option database.
Guido van Rossum5917ecb2000-06-29 16:30:50 +0000645
Fredrik Lundh06d28152000-08-09 18:03:12 +0000646 It will be reloaded if option_add is called."""
647 self.tk.call('option', 'clear')
648 def option_get(self, name, className):
649 """Return the value for an option NAME for this widget
650 with CLASSNAME.
Guido van Rossum5917ecb2000-06-29 16:30:50 +0000651
Fredrik Lundh06d28152000-08-09 18:03:12 +0000652 Values with higher priority override lower values."""
653 return self.tk.call('option', 'get', self._w, name, className)
654 def option_readfile(self, fileName, priority = None):
655 """Read file FILENAME into the option database.
Guido van Rossum5917ecb2000-06-29 16:30:50 +0000656
Fredrik Lundh06d28152000-08-09 18:03:12 +0000657 An optional second parameter gives the numeric
658 priority."""
659 self.tk.call('option', 'readfile', fileName, priority)
660 def selection_clear(self, **kw):
661 """Clear the current X selection."""
Guido van Rossume014a132006-08-19 16:53:45 +0000662 if 'displayof' not in kw: kw['displayof'] = self._w
Fredrik Lundh06d28152000-08-09 18:03:12 +0000663 self.tk.call(('selection', 'clear') + self._options(kw))
664 def selection_get(self, **kw):
665 """Return the contents of the current X selection.
Guido van Rossum5917ecb2000-06-29 16:30:50 +0000666
Fredrik Lundh06d28152000-08-09 18:03:12 +0000667 A keyword parameter selection specifies the name of
668 the selection and defaults to PRIMARY. A keyword
669 parameter displayof specifies a widget on the display
Ned Deily4d377d92012-05-15 18:08:11 -0700670 to use. A keyword parameter type specifies the form of data to be
671 fetched, defaulting to STRING except on X11, where UTF8_STRING is tried
672 before STRING."""
Guido van Rossume014a132006-08-19 16:53:45 +0000673 if 'displayof' not in kw: kw['displayof'] = self._w
Ned Deily4d377d92012-05-15 18:08:11 -0700674 if 'type' not in kw and self._windowingsystem == 'x11':
675 try:
676 kw['type'] = 'UTF8_STRING'
677 return self.tk.call(('selection', 'get') + self._options(kw))
678 except TclError:
679 del kw['type']
Fredrik Lundh06d28152000-08-09 18:03:12 +0000680 return self.tk.call(('selection', 'get') + self._options(kw))
681 def selection_handle(self, command, **kw):
682 """Specify a function COMMAND to call if the X
683 selection owned by this widget is queried by another
684 application.
Guido van Rossum5917ecb2000-06-29 16:30:50 +0000685
Fredrik Lundh06d28152000-08-09 18:03:12 +0000686 This function must return the contents of the
687 selection. The function will be called with the
688 arguments OFFSET and LENGTH which allows the chunking
689 of very long selections. The following keyword
690 parameters can be provided:
691 selection - name of the selection (default PRIMARY),
692 type - type of the selection (e.g. STRING, FILE_NAME)."""
693 name = self._register(command)
694 self.tk.call(('selection', 'handle') + self._options(kw)
695 + (self._w, name))
696 def selection_own(self, **kw):
697 """Become owner of X selection.
Guido van Rossum5917ecb2000-06-29 16:30:50 +0000698
Fredrik Lundh06d28152000-08-09 18:03:12 +0000699 A keyword parameter selection specifies the name of
700 the selection (default PRIMARY)."""
701 self.tk.call(('selection', 'own') +
702 self._options(kw) + (self._w,))
703 def selection_own_get(self, **kw):
704 """Return owner of X selection.
Guido van Rossum5917ecb2000-06-29 16:30:50 +0000705
Fredrik Lundh06d28152000-08-09 18:03:12 +0000706 The following keyword parameter can
707 be provided:
708 selection - name of the selection (default PRIMARY),
709 type - type of the selection (e.g. STRING, FILE_NAME)."""
Guido van Rossume014a132006-08-19 16:53:45 +0000710 if 'displayof' not in kw: kw['displayof'] = self._w
Fredrik Lundh06d28152000-08-09 18:03:12 +0000711 name = self.tk.call(('selection', 'own') + self._options(kw))
712 if not name: return None
713 return self._nametowidget(name)
714 def send(self, interp, cmd, *args):
715 """Send Tcl command CMD to different interpreter INTERP to be executed."""
716 return self.tk.call(('send', interp, cmd) + args)
717 def lower(self, belowThis=None):
718 """Lower this widget in the stacking order."""
719 self.tk.call('lower', self._w, belowThis)
720 def tkraise(self, aboveThis=None):
721 """Raise this widget in the stacking order."""
722 self.tk.call('raise', self._w, aboveThis)
723 lift = tkraise
724 def colormodel(self, value=None):
725 """Useless. Not implemented in Tk."""
726 return self.tk.call('tk', 'colormodel', self._w, value)
727 def winfo_atom(self, name, displayof=0):
728 """Return integer which represents atom NAME."""
729 args = ('winfo', 'atom') + self._displayof(displayof) + (name,)
730 return getint(self.tk.call(args))
731 def winfo_atomname(self, id, displayof=0):
732 """Return name of atom with identifier ID."""
733 args = ('winfo', 'atomname') \
734 + self._displayof(displayof) + (id,)
735 return self.tk.call(args)
736 def winfo_cells(self):
737 """Return number of cells in the colormap for this widget."""
738 return getint(
739 self.tk.call('winfo', 'cells', self._w))
740 def winfo_children(self):
741 """Return a list of all widgets which are children of this widget."""
Martin v. Löwisf2041b82002-03-27 17:15:57 +0000742 result = []
743 for child in self.tk.splitlist(
744 self.tk.call('winfo', 'children', self._w)):
745 try:
746 # Tcl sometimes returns extra windows, e.g. for
747 # menus; those need to be skipped
748 result.append(self._nametowidget(child))
749 except KeyError:
750 pass
751 return result
752
Fredrik Lundh06d28152000-08-09 18:03:12 +0000753 def winfo_class(self):
754 """Return window class name of this widget."""
755 return self.tk.call('winfo', 'class', self._w)
756 def winfo_colormapfull(self):
757 """Return true if at the last color request the colormap was full."""
758 return self.tk.getboolean(
759 self.tk.call('winfo', 'colormapfull', self._w))
760 def winfo_containing(self, rootX, rootY, displayof=0):
761 """Return the widget which is at the root coordinates ROOTX, ROOTY."""
762 args = ('winfo', 'containing') \
763 + self._displayof(displayof) + (rootX, rootY)
764 name = self.tk.call(args)
765 if not name: return None
766 return self._nametowidget(name)
767 def winfo_depth(self):
768 """Return the number of bits per pixel."""
769 return getint(self.tk.call('winfo', 'depth', self._w))
770 def winfo_exists(self):
771 """Return true if this widget exists."""
772 return getint(
773 self.tk.call('winfo', 'exists', self._w))
774 def winfo_fpixels(self, number):
775 """Return the number of pixels for the given distance NUMBER
776 (e.g. "3c") as float."""
777 return getdouble(self.tk.call(
778 'winfo', 'fpixels', self._w, number))
779 def winfo_geometry(self):
780 """Return geometry string for this widget in the form "widthxheight+X+Y"."""
781 return self.tk.call('winfo', 'geometry', self._w)
782 def winfo_height(self):
783 """Return height of this widget."""
784 return getint(
785 self.tk.call('winfo', 'height', self._w))
786 def winfo_id(self):
787 """Return identifier ID for this widget."""
788 return self.tk.getint(
789 self.tk.call('winfo', 'id', self._w))
790 def winfo_interps(self, displayof=0):
791 """Return the name of all Tcl interpreters for this display."""
792 args = ('winfo', 'interps') + self._displayof(displayof)
793 return self.tk.splitlist(self.tk.call(args))
794 def winfo_ismapped(self):
795 """Return true if this widget is mapped."""
796 return getint(
797 self.tk.call('winfo', 'ismapped', self._w))
798 def winfo_manager(self):
799 """Return the window mananger name for this widget."""
800 return self.tk.call('winfo', 'manager', self._w)
801 def winfo_name(self):
802 """Return the name of this widget."""
803 return self.tk.call('winfo', 'name', self._w)
804 def winfo_parent(self):
805 """Return the name of the parent of this widget."""
806 return self.tk.call('winfo', 'parent', self._w)
807 def winfo_pathname(self, id, displayof=0):
808 """Return the pathname of the widget given by ID."""
809 args = ('winfo', 'pathname') \
810 + self._displayof(displayof) + (id,)
811 return self.tk.call(args)
812 def winfo_pixels(self, number):
813 """Rounded integer value of winfo_fpixels."""
814 return getint(
815 self.tk.call('winfo', 'pixels', self._w, number))
816 def winfo_pointerx(self):
817 """Return the x coordinate of the pointer on the root window."""
818 return getint(
819 self.tk.call('winfo', 'pointerx', self._w))
820 def winfo_pointerxy(self):
821 """Return a tuple of x and y coordinates of the pointer on the root window."""
822 return self._getints(
823 self.tk.call('winfo', 'pointerxy', self._w))
824 def winfo_pointery(self):
825 """Return the y coordinate of the pointer on the root window."""
826 return getint(
827 self.tk.call('winfo', 'pointery', self._w))
828 def winfo_reqheight(self):
829 """Return requested height of this widget."""
830 return getint(
831 self.tk.call('winfo', 'reqheight', self._w))
832 def winfo_reqwidth(self):
833 """Return requested width of this widget."""
834 return getint(
835 self.tk.call('winfo', 'reqwidth', self._w))
836 def winfo_rgb(self, color):
837 """Return tuple of decimal values for red, green, blue for
838 COLOR in this widget."""
839 return self._getints(
840 self.tk.call('winfo', 'rgb', self._w, color))
841 def winfo_rootx(self):
842 """Return x coordinate of upper left corner of this widget on the
843 root window."""
844 return getint(
845 self.tk.call('winfo', 'rootx', self._w))
846 def winfo_rooty(self):
847 """Return y coordinate of upper left corner of this widget on the
848 root window."""
849 return getint(
850 self.tk.call('winfo', 'rooty', self._w))
851 def winfo_screen(self):
852 """Return the screen name of this widget."""
853 return self.tk.call('winfo', 'screen', self._w)
854 def winfo_screencells(self):
855 """Return the number of the cells in the colormap of the screen
856 of this widget."""
857 return getint(
858 self.tk.call('winfo', 'screencells', self._w))
859 def winfo_screendepth(self):
860 """Return the number of bits per pixel of the root window of the
861 screen of this widget."""
862 return getint(
863 self.tk.call('winfo', 'screendepth', self._w))
864 def winfo_screenheight(self):
865 """Return the number of pixels of the height of the screen of this widget
866 in pixel."""
867 return getint(
868 self.tk.call('winfo', 'screenheight', self._w))
869 def winfo_screenmmheight(self):
870 """Return the number of pixels of the height of the screen of
871 this widget in mm."""
872 return getint(
873 self.tk.call('winfo', 'screenmmheight', self._w))
874 def winfo_screenmmwidth(self):
875 """Return the number of pixels of the width of the screen of
876 this widget in mm."""
877 return getint(
878 self.tk.call('winfo', 'screenmmwidth', self._w))
879 def winfo_screenvisual(self):
880 """Return one of the strings directcolor, grayscale, pseudocolor,
881 staticcolor, staticgray, or truecolor for the default
882 colormodel of this screen."""
883 return self.tk.call('winfo', 'screenvisual', self._w)
884 def winfo_screenwidth(self):
885 """Return the number of pixels of the width of the screen of
886 this widget in pixel."""
887 return getint(
888 self.tk.call('winfo', 'screenwidth', self._w))
889 def winfo_server(self):
890 """Return information of the X-Server of the screen of this widget in
891 the form "XmajorRminor vendor vendorVersion"."""
892 return self.tk.call('winfo', 'server', self._w)
893 def winfo_toplevel(self):
894 """Return the toplevel widget of this widget."""
895 return self._nametowidget(self.tk.call(
896 'winfo', 'toplevel', self._w))
897 def winfo_viewable(self):
898 """Return true if the widget and all its higher ancestors are mapped."""
899 return getint(
900 self.tk.call('winfo', 'viewable', self._w))
901 def winfo_visual(self):
902 """Return one of the strings directcolor, grayscale, pseudocolor,
903 staticcolor, staticgray, or truecolor for the
904 colormodel of this widget."""
905 return self.tk.call('winfo', 'visual', self._w)
906 def winfo_visualid(self):
907 """Return the X identifier for the visual for this widget."""
908 return self.tk.call('winfo', 'visualid', self._w)
909 def winfo_visualsavailable(self, includeids=0):
910 """Return a list of all visuals available for the screen
911 of this widget.
Guido van Rossum5917ecb2000-06-29 16:30:50 +0000912
Fredrik Lundh06d28152000-08-09 18:03:12 +0000913 Each item in the list consists of a visual name (see winfo_visual), a
914 depth and if INCLUDEIDS=1 is given also the X identifier."""
915 data = self.tk.split(
916 self.tk.call('winfo', 'visualsavailable', self._w,
917 includeids and 'includeids' or None))
Guido van Rossum13257902007-06-07 23:15:56 +0000918 if isinstance(data, str):
Fredrik Lundh24037f72000-08-09 19:26:47 +0000919 data = [self.tk.split(data)]
Alexander Belopolsky022f0492010-11-22 19:40:51 +0000920 return [self.__winfo_parseitem(x) for x in data]
Fredrik Lundh06d28152000-08-09 18:03:12 +0000921 def __winfo_parseitem(self, t):
922 """Internal function."""
923 return t[:1] + tuple(map(self.__winfo_getint, t[1:]))
924 def __winfo_getint(self, x):
925 """Internal function."""
Eric S. Raymondfc170b12001-02-09 11:51:27 +0000926 return int(x, 0)
Fredrik Lundh06d28152000-08-09 18:03:12 +0000927 def winfo_vrootheight(self):
928 """Return the height of the virtual root window associated with this
929 widget in pixels. If there is no virtual root window return the
930 height of the screen."""
931 return getint(
932 self.tk.call('winfo', 'vrootheight', self._w))
933 def winfo_vrootwidth(self):
934 """Return the width of the virtual root window associated with this
935 widget in pixel. If there is no virtual root window return the
936 width of the screen."""
937 return getint(
938 self.tk.call('winfo', 'vrootwidth', self._w))
939 def winfo_vrootx(self):
940 """Return the x offset of the virtual root relative to the root
941 window of the screen of this widget."""
942 return getint(
943 self.tk.call('winfo', 'vrootx', self._w))
944 def winfo_vrooty(self):
945 """Return the y offset of the virtual root relative to the root
946 window of the screen of this widget."""
947 return getint(
948 self.tk.call('winfo', 'vrooty', self._w))
949 def winfo_width(self):
950 """Return the width of this widget."""
951 return getint(
952 self.tk.call('winfo', 'width', self._w))
953 def winfo_x(self):
954 """Return the x coordinate of the upper left corner of this widget
955 in the parent."""
956 return getint(
957 self.tk.call('winfo', 'x', self._w))
958 def winfo_y(self):
959 """Return the y coordinate of the upper left corner of this widget
960 in the parent."""
961 return getint(
962 self.tk.call('winfo', 'y', self._w))
963 def update(self):
964 """Enter event loop until all pending events have been processed by Tcl."""
965 self.tk.call('update')
966 def update_idletasks(self):
967 """Enter event loop until all idle callbacks have been called. This
968 will update the display of windows but not process events caused by
969 the user."""
970 self.tk.call('update', 'idletasks')
971 def bindtags(self, tagList=None):
972 """Set or get the list of bindtags for this widget.
Guido van Rossum5917ecb2000-06-29 16:30:50 +0000973
Fredrik Lundh06d28152000-08-09 18:03:12 +0000974 With no argument return the list of all bindtags associated with
975 this widget. With a list of strings as argument the bindtags are
976 set to this list. The bindtags determine in which order events are
977 processed (see bind)."""
978 if tagList is None:
979 return self.tk.splitlist(
980 self.tk.call('bindtags', self._w))
981 else:
982 self.tk.call('bindtags', self._w, tagList)
983 def _bind(self, what, sequence, func, add, needcleanup=1):
984 """Internal function."""
Guido van Rossum13257902007-06-07 23:15:56 +0000985 if isinstance(func, str):
Fredrik Lundh06d28152000-08-09 18:03:12 +0000986 self.tk.call(what + (sequence, func))
987 elif func:
988 funcid = self._register(func, self._substitute,
989 needcleanup)
990 cmd = ('%sif {"[%s %s]" == "break"} break\n'
991 %
992 (add and '+' or '',
Martin v. Löwisc8718c12001-08-09 16:57:33 +0000993 funcid, self._subst_format_str))
Fredrik Lundh06d28152000-08-09 18:03:12 +0000994 self.tk.call(what + (sequence, cmd))
995 return funcid
996 elif sequence:
997 return self.tk.call(what + (sequence,))
998 else:
999 return self.tk.splitlist(self.tk.call(what))
1000 def bind(self, sequence=None, func=None, add=None):
1001 """Bind to this widget at event SEQUENCE a call to function FUNC.
Guido van Rossum5917ecb2000-06-29 16:30:50 +00001002
Fredrik Lundh06d28152000-08-09 18:03:12 +00001003 SEQUENCE is a string of concatenated event
1004 patterns. An event pattern is of the form
1005 <MODIFIER-MODIFIER-TYPE-DETAIL> where MODIFIER is one
1006 of Control, Mod2, M2, Shift, Mod3, M3, Lock, Mod4, M4,
1007 Button1, B1, Mod5, M5 Button2, B2, Meta, M, Button3,
1008 B3, Alt, Button4, B4, Double, Button5, B5 Triple,
1009 Mod1, M1. TYPE is one of Activate, Enter, Map,
1010 ButtonPress, Button, Expose, Motion, ButtonRelease
1011 FocusIn, MouseWheel, Circulate, FocusOut, Property,
1012 Colormap, Gravity Reparent, Configure, KeyPress, Key,
1013 Unmap, Deactivate, KeyRelease Visibility, Destroy,
1014 Leave and DETAIL is the button number for ButtonPress,
1015 ButtonRelease and DETAIL is the Keysym for KeyPress and
1016 KeyRelease. Examples are
1017 <Control-Button-1> for pressing Control and mouse button 1 or
1018 <Alt-A> for pressing A and the Alt key (KeyPress can be omitted).
1019 An event pattern can also be a virtual event of the form
1020 <<AString>> where AString can be arbitrary. This
1021 event can be generated by event_generate.
1022 If events are concatenated they must appear shortly
1023 after each other.
Guido van Rossum5917ecb2000-06-29 16:30:50 +00001024
Fredrik Lundh06d28152000-08-09 18:03:12 +00001025 FUNC will be called if the event sequence occurs with an
1026 instance of Event as argument. If the return value of FUNC is
1027 "break" no further bound function is invoked.
Guido van Rossum5917ecb2000-06-29 16:30:50 +00001028
Fredrik Lundh06d28152000-08-09 18:03:12 +00001029 An additional boolean parameter ADD specifies whether FUNC will
1030 be called additionally to the other bound function or whether
1031 it will replace the previous function.
Guido van Rossum5917ecb2000-06-29 16:30:50 +00001032
Fredrik Lundh06d28152000-08-09 18:03:12 +00001033 Bind will return an identifier to allow deletion of the bound function with
1034 unbind without memory leak.
Guido van Rossum5917ecb2000-06-29 16:30:50 +00001035
Fredrik Lundh06d28152000-08-09 18:03:12 +00001036 If FUNC or SEQUENCE is omitted the bound function or list
1037 of bound events are returned."""
Guido van Rossum5917ecb2000-06-29 16:30:50 +00001038
Fredrik Lundh06d28152000-08-09 18:03:12 +00001039 return self._bind(('bind', self._w), sequence, func, add)
1040 def unbind(self, sequence, funcid=None):
1041 """Unbind for this widget for event SEQUENCE the
1042 function identified with FUNCID."""
1043 self.tk.call('bind', self._w, sequence, '')
1044 if funcid:
1045 self.deletecommand(funcid)
1046 def bind_all(self, sequence=None, func=None, add=None):
1047 """Bind to all widgets at an event SEQUENCE a call to function FUNC.
1048 An additional boolean parameter ADD specifies whether FUNC will
1049 be called additionally to the other bound function or whether
1050 it will replace the previous function. See bind for the return value."""
1051 return self._bind(('bind', 'all'), sequence, func, add, 0)
1052 def unbind_all(self, sequence):
1053 """Unbind for all widgets for event SEQUENCE all functions."""
1054 self.tk.call('bind', 'all' , sequence, '')
1055 def bind_class(self, className, sequence=None, func=None, add=None):
Guido van Rossum5917ecb2000-06-29 16:30:50 +00001056
Fredrik Lundh06d28152000-08-09 18:03:12 +00001057 """Bind to widgets with bindtag CLASSNAME at event
1058 SEQUENCE a call of function FUNC. An additional
1059 boolean parameter ADD specifies whether FUNC will be
1060 called additionally to the other bound function or
1061 whether it will replace the previous function. See bind for
1062 the return value."""
Guido van Rossum5917ecb2000-06-29 16:30:50 +00001063
Fredrik Lundh06d28152000-08-09 18:03:12 +00001064 return self._bind(('bind', className), sequence, func, add, 0)
1065 def unbind_class(self, className, sequence):
1066 """Unbind for a all widgets with bindtag CLASSNAME for event SEQUENCE
1067 all functions."""
1068 self.tk.call('bind', className , sequence, '')
1069 def mainloop(self, n=0):
1070 """Call the mainloop of Tk."""
1071 self.tk.mainloop(n)
1072 def quit(self):
1073 """Quit the Tcl interpreter. All widgets will be destroyed."""
1074 self.tk.quit()
1075 def _getints(self, string):
1076 """Internal function."""
1077 if string:
1078 return tuple(map(getint, self.tk.splitlist(string)))
1079 def _getdoubles(self, string):
1080 """Internal function."""
1081 if string:
1082 return tuple(map(getdouble, self.tk.splitlist(string)))
1083 def _getboolean(self, string):
1084 """Internal function."""
1085 if string:
1086 return self.tk.getboolean(string)
1087 def _displayof(self, displayof):
1088 """Internal function."""
1089 if displayof:
1090 return ('-displayof', displayof)
1091 if displayof is None:
1092 return ('-displayof', self._w)
1093 return ()
Ned Deily4d377d92012-05-15 18:08:11 -07001094 @property
1095 def _windowingsystem(self):
1096 """Internal function."""
1097 try:
1098 return self._root()._windowingsystem_cached
1099 except AttributeError:
1100 ws = self._root()._windowingsystem_cached = \
1101 self.tk.call('tk', 'windowingsystem')
1102 return ws
Fredrik Lundh06d28152000-08-09 18:03:12 +00001103 def _options(self, cnf, kw = None):
1104 """Internal function."""
1105 if kw:
1106 cnf = _cnfmerge((cnf, kw))
1107 else:
1108 cnf = _cnfmerge(cnf)
1109 res = ()
1110 for k, v in cnf.items():
1111 if v is not None:
1112 if k[-1] == '_': k = k[:-1]
Florent Xicluna5d1155c2011-10-28 14:45:05 +02001113 if callable(v):
Fredrik Lundh06d28152000-08-09 18:03:12 +00001114 v = self._register(v)
Georg Brandlbf1eb632008-05-29 07:19:00 +00001115 elif isinstance(v, (tuple, list)):
Georg Brandl3b550032008-06-03 10:25:47 +00001116 nv = []
Georg Brandlbf1eb632008-05-29 07:19:00 +00001117 for item in v:
Georg Brandl3b550032008-06-03 10:25:47 +00001118 if isinstance(item, int):
1119 nv.append(str(item))
1120 elif isinstance(item, str):
Serhiy Storchakab1396522013-01-15 17:56:08 +02001121 nv.append(_stringify(item))
Georg Brandl3b550032008-06-03 10:25:47 +00001122 else:
Georg Brandlbf1eb632008-05-29 07:19:00 +00001123 break
1124 else:
Georg Brandl3b550032008-06-03 10:25:47 +00001125 v = ' '.join(nv)
Fredrik Lundh06d28152000-08-09 18:03:12 +00001126 res = res + ('-'+k, v)
1127 return res
1128 def nametowidget(self, name):
1129 """Return the Tkinter instance of a widget identified by
1130 its Tcl name NAME."""
Martin v. Löwiscdfae162008-08-02 07:23:15 +00001131 name = str(name).split('.')
Fredrik Lundh06d28152000-08-09 18:03:12 +00001132 w = self
Martin v. Löwiscdfae162008-08-02 07:23:15 +00001133
1134 if not name[0]:
Fredrik Lundh06d28152000-08-09 18:03:12 +00001135 w = w._root()
1136 name = name[1:]
Martin v. Löwiscdfae162008-08-02 07:23:15 +00001137
1138 for n in name:
1139 if not n:
1140 break
1141 w = w.children[n]
1142
Fredrik Lundh06d28152000-08-09 18:03:12 +00001143 return w
1144 _nametowidget = nametowidget
1145 def _register(self, func, subst=None, needcleanup=1):
1146 """Return a newly created Tcl function. If this
1147 function is called, the Python function FUNC will
1148 be executed. An optional function SUBST can
1149 be given which will be executed before FUNC."""
1150 f = CallWrapper(func, subst, self).__call__
Walter Dörwald70a6b492004-02-12 17:35:32 +00001151 name = repr(id(f))
Fredrik Lundh06d28152000-08-09 18:03:12 +00001152 try:
Christian Heimesff737952007-11-27 10:40:20 +00001153 func = func.__func__
Fredrik Lundh06d28152000-08-09 18:03:12 +00001154 except AttributeError:
1155 pass
1156 try:
1157 name = name + func.__name__
1158 except AttributeError:
1159 pass
1160 self.tk.createcommand(name, f)
1161 if needcleanup:
1162 if self._tclCommands is None:
1163 self._tclCommands = []
1164 self._tclCommands.append(name)
Fredrik Lundh06d28152000-08-09 18:03:12 +00001165 return name
1166 register = _register
1167 def _root(self):
1168 """Internal function."""
1169 w = self
1170 while w.master: w = w.master
1171 return w
1172 _subst_format = ('%#', '%b', '%f', '%h', '%k',
1173 '%s', '%t', '%w', '%x', '%y',
1174 '%A', '%E', '%K', '%N', '%W', '%T', '%X', '%Y', '%D')
Martin v. Löwisc8718c12001-08-09 16:57:33 +00001175 _subst_format_str = " ".join(_subst_format)
Fredrik Lundh06d28152000-08-09 18:03:12 +00001176 def _substitute(self, *args):
1177 """Internal function."""
1178 if len(args) != len(self._subst_format): return args
1179 getboolean = self.tk.getboolean
Martin v. Löwis043bbc72003-03-29 09:47:21 +00001180
Fredrik Lundh06d28152000-08-09 18:03:12 +00001181 getint = int
Martin v. Löwis043bbc72003-03-29 09:47:21 +00001182 def getint_event(s):
1183 """Tk changed behavior in 8.4.2, returning "??" rather more often."""
1184 try:
1185 return int(s)
1186 except ValueError:
1187 return s
1188
Fredrik Lundh06d28152000-08-09 18:03:12 +00001189 nsign, b, f, h, k, s, t, w, x, y, A, E, K, N, W, T, X, Y, D = args
1190 # Missing: (a, c, d, m, o, v, B, R)
1191 e = Event()
Martin v. Löwis043bbc72003-03-29 09:47:21 +00001192 # serial field: valid vor all events
1193 # number of button: ButtonPress and ButtonRelease events only
1194 # height field: Configure, ConfigureRequest, Create,
1195 # ResizeRequest, and Expose events only
1196 # keycode field: KeyPress and KeyRelease events only
1197 # time field: "valid for events that contain a time field"
1198 # width field: Configure, ConfigureRequest, Create, ResizeRequest,
1199 # and Expose events only
1200 # x field: "valid for events that contain a x field"
1201 # y field: "valid for events that contain a y field"
1202 # keysym as decimal: KeyPress and KeyRelease events only
1203 # x_root, y_root fields: ButtonPress, ButtonRelease, KeyPress,
1204 # KeyRelease,and Motion events
Fredrik Lundh06d28152000-08-09 18:03:12 +00001205 e.serial = getint(nsign)
Martin v. Löwis043bbc72003-03-29 09:47:21 +00001206 e.num = getint_event(b)
Fredrik Lundh06d28152000-08-09 18:03:12 +00001207 try: e.focus = getboolean(f)
1208 except TclError: pass
Martin v. Löwis043bbc72003-03-29 09:47:21 +00001209 e.height = getint_event(h)
1210 e.keycode = getint_event(k)
1211 e.state = getint_event(s)
1212 e.time = getint_event(t)
1213 e.width = getint_event(w)
1214 e.x = getint_event(x)
1215 e.y = getint_event(y)
Fredrik Lundh06d28152000-08-09 18:03:12 +00001216 e.char = A
1217 try: e.send_event = getboolean(E)
1218 except TclError: pass
1219 e.keysym = K
Martin v. Löwis043bbc72003-03-29 09:47:21 +00001220 e.keysym_num = getint_event(N)
Fredrik Lundh06d28152000-08-09 18:03:12 +00001221 e.type = T
1222 try:
1223 e.widget = self._nametowidget(W)
1224 except KeyError:
1225 e.widget = W
Martin v. Löwis043bbc72003-03-29 09:47:21 +00001226 e.x_root = getint_event(X)
1227 e.y_root = getint_event(Y)
Fredrik Lundha249f162000-09-07 15:05:09 +00001228 try:
1229 e.delta = getint(D)
1230 except ValueError:
1231 e.delta = 0
Fredrik Lundh06d28152000-08-09 18:03:12 +00001232 return (e,)
1233 def _report_exception(self):
1234 """Internal function."""
Neal Norwitzac3625f2006-03-17 05:49:33 +00001235 exc, val, tb = sys.exc_info()
Fredrik Lundh06d28152000-08-09 18:03:12 +00001236 root = self._root()
1237 root.report_callback_exception(exc, val, tb)
Martin v. Löwis6ce13152002-10-10 14:36:13 +00001238 def _configure(self, cmd, cnf, kw):
1239 """Internal function."""
1240 if kw:
1241 cnf = _cnfmerge((cnf, kw))
1242 elif cnf:
1243 cnf = _cnfmerge(cnf)
1244 if cnf is None:
1245 cnf = {}
1246 for x in self.tk.split(
1247 self.tk.call(_flatten((self._w, cmd)))):
1248 cnf[x[0][1:]] = (x[0][1:],) + x[1:]
1249 return cnf
Guido van Rossum13257902007-06-07 23:15:56 +00001250 if isinstance(cnf, str):
Martin v. Löwis6ce13152002-10-10 14:36:13 +00001251 x = self.tk.split(
1252 self.tk.call(_flatten((self._w, cmd, '-'+cnf))))
1253 return (x[0][1:],) + x[1:]
1254 self.tk.call(_flatten((self._w, cmd)) + self._options(cnf))
Fredrik Lundh06d28152000-08-09 18:03:12 +00001255 # These used to be defined in Widget:
1256 def configure(self, cnf=None, **kw):
1257 """Configure resources of a widget.
Barry Warsaw107e6231998-12-15 00:44:15 +00001258
Fredrik Lundh06d28152000-08-09 18:03:12 +00001259 The values for resources are specified as keyword
1260 arguments. To get an overview about
1261 the allowed keyword arguments call the method keys.
1262 """
Martin v. Löwis6ce13152002-10-10 14:36:13 +00001263 return self._configure('configure', cnf, kw)
Fredrik Lundh06d28152000-08-09 18:03:12 +00001264 config = configure
1265 def cget(self, key):
1266 """Return the resource value for a KEY given as string."""
1267 return self.tk.call(self._w, 'cget', '-' + key)
1268 __getitem__ = cget
1269 def __setitem__(self, key, value):
1270 self.configure({key: value})
1271 def keys(self):
1272 """Return a list of all resource names of this widget."""
Alexander Belopolsky022f0492010-11-22 19:40:51 +00001273 return [x[0][1:] for x in
1274 self.tk.split(self.tk.call(self._w, 'configure'))]
Fredrik Lundh06d28152000-08-09 18:03:12 +00001275 def __str__(self):
1276 """Return the window path name of this widget."""
1277 return self._w
1278 # Pack methods that apply to the master
1279 _noarg_ = ['_noarg_']
1280 def pack_propagate(self, flag=_noarg_):
1281 """Set or get the status for propagation of geometry information.
Guido van Rossum5917ecb2000-06-29 16:30:50 +00001282
Fredrik Lundh06d28152000-08-09 18:03:12 +00001283 A boolean argument specifies whether the geometry information
1284 of the slaves will determine the size of this widget. If no argument
1285 is given the current setting will be returned.
1286 """
1287 if flag is Misc._noarg_:
1288 return self._getboolean(self.tk.call(
1289 'pack', 'propagate', self._w))
1290 else:
1291 self.tk.call('pack', 'propagate', self._w, flag)
1292 propagate = pack_propagate
1293 def pack_slaves(self):
1294 """Return a list of all slaves of this widget
1295 in its packing order."""
Alexander Belopolsky022f0492010-11-22 19:40:51 +00001296 return [self._nametowidget(x) for x in
1297 self.tk.splitlist(
1298 self.tk.call('pack', 'slaves', self._w))]
Fredrik Lundh06d28152000-08-09 18:03:12 +00001299 slaves = pack_slaves
1300 # Place method that applies to the master
1301 def place_slaves(self):
1302 """Return a list of all slaves of this widget
1303 in its packing order."""
Alexander Belopolsky022f0492010-11-22 19:40:51 +00001304 return [self._nametowidget(x) for x in
1305 self.tk.splitlist(
Fredrik Lundh06d28152000-08-09 18:03:12 +00001306 self.tk.call(
Alexander Belopolsky022f0492010-11-22 19:40:51 +00001307 'place', 'slaves', self._w))]
Fredrik Lundh06d28152000-08-09 18:03:12 +00001308 # Grid methods that apply to the master
Martin v. Löwis5c3c4242012-03-13 13:40:42 -07001309 def grid_anchor(self, anchor=None): # new in Tk 8.5
1310 """The anchor value controls how to place the grid within the
1311 master when no row/column has any weight.
1312
1313 The default anchor is nw."""
1314 self.tk.call('grid', 'anchor', self._w, anchor)
1315 anchor = grid_anchor
Fredrik Lundh06d28152000-08-09 18:03:12 +00001316 def grid_bbox(self, column=None, row=None, col2=None, row2=None):
1317 """Return a tuple of integer coordinates for the bounding
1318 box of this widget controlled by the geometry manager grid.
Guido van Rossum5917ecb2000-06-29 16:30:50 +00001319
Fredrik Lundh06d28152000-08-09 18:03:12 +00001320 If COLUMN, ROW is given the bounding box applies from
1321 the cell with row and column 0 to the specified
1322 cell. If COL2 and ROW2 are given the bounding box
1323 starts at that cell.
Guido van Rossum5917ecb2000-06-29 16:30:50 +00001324
Fredrik Lundh06d28152000-08-09 18:03:12 +00001325 The returned integers specify the offset of the upper left
1326 corner in the master widget and the width and height.
1327 """
1328 args = ('grid', 'bbox', self._w)
1329 if column is not None and row is not None:
1330 args = args + (column, row)
1331 if col2 is not None and row2 is not None:
1332 args = args + (col2, row2)
Raymond Hettingerff41c482003-04-06 09:01:11 +00001333 return self._getints(self.tk.call(*args)) or None
Fredrik Lundh06d28152000-08-09 18:03:12 +00001334 bbox = grid_bbox
1335 def _grid_configure(self, command, index, cnf, kw):
1336 """Internal function."""
Guido van Rossum13257902007-06-07 23:15:56 +00001337 if isinstance(cnf, str) and not kw:
Fredrik Lundh06d28152000-08-09 18:03:12 +00001338 if cnf[-1:] == '_':
1339 cnf = cnf[:-1]
1340 if cnf[:1] != '-':
1341 cnf = '-'+cnf
1342 options = (cnf,)
1343 else:
1344 options = self._options(cnf, kw)
1345 if not options:
1346 res = self.tk.call('grid',
1347 command, self._w, index)
1348 words = self.tk.splitlist(res)
1349 dict = {}
1350 for i in range(0, len(words), 2):
1351 key = words[i][1:]
1352 value = words[i+1]
1353 if not value:
1354 value = None
1355 elif '.' in value:
1356 value = getdouble(value)
1357 else:
1358 value = getint(value)
1359 dict[key] = value
1360 return dict
1361 res = self.tk.call(
1362 ('grid', command, self._w, index)
1363 + options)
1364 if len(options) == 1:
1365 if not res: return None
1366 # In Tk 7.5, -width can be a float
1367 if '.' in res: return getdouble(res)
1368 return getint(res)
1369 def grid_columnconfigure(self, index, cnf={}, **kw):
1370 """Configure column INDEX of a grid.
Guido van Rossum80f8be81997-12-02 19:51:39 +00001371
Fredrik Lundh06d28152000-08-09 18:03:12 +00001372 Valid resources are minsize (minimum size of the column),
1373 weight (how much does additional space propagate to this column)
1374 and pad (how much space to let additionally)."""
1375 return self._grid_configure('columnconfigure', index, cnf, kw)
1376 columnconfigure = grid_columnconfigure
Martin v. Löwisdc579092001-10-13 09:33:51 +00001377 def grid_location(self, x, y):
1378 """Return a tuple of column and row which identify the cell
1379 at which the pixel at position X and Y inside the master
1380 widget is located."""
1381 return self._getints(
1382 self.tk.call(
1383 'grid', 'location', self._w, x, y)) or None
Fredrik Lundh06d28152000-08-09 18:03:12 +00001384 def grid_propagate(self, flag=_noarg_):
1385 """Set or get the status for propagation of geometry information.
Guido van Rossum80f8be81997-12-02 19:51:39 +00001386
Fredrik Lundh06d28152000-08-09 18:03:12 +00001387 A boolean argument specifies whether the geometry information
1388 of the slaves will determine the size of this widget. If no argument
1389 is given, the current setting will be returned.
1390 """
1391 if flag is Misc._noarg_:
1392 return self._getboolean(self.tk.call(
1393 'grid', 'propagate', self._w))
1394 else:
1395 self.tk.call('grid', 'propagate', self._w, flag)
1396 def grid_rowconfigure(self, index, cnf={}, **kw):
1397 """Configure row INDEX of a grid.
Guido van Rossum80f8be81997-12-02 19:51:39 +00001398
Fredrik Lundh06d28152000-08-09 18:03:12 +00001399 Valid resources are minsize (minimum size of the row),
1400 weight (how much does additional space propagate to this row)
1401 and pad (how much space to let additionally)."""
1402 return self._grid_configure('rowconfigure', index, cnf, kw)
1403 rowconfigure = grid_rowconfigure
1404 def grid_size(self):
1405 """Return a tuple of the number of column and rows in the grid."""
1406 return self._getints(
1407 self.tk.call('grid', 'size', self._w)) or None
1408 size = grid_size
1409 def grid_slaves(self, row=None, column=None):
1410 """Return a list of all slaves of this widget
1411 in its packing order."""
1412 args = ()
1413 if row is not None:
1414 args = args + ('-row', row)
1415 if column is not None:
1416 args = args + ('-column', column)
Alexander Belopolsky022f0492010-11-22 19:40:51 +00001417 return [self._nametowidget(x) for x in
1418 self.tk.splitlist(self.tk.call(
1419 ('grid', 'slaves', self._w) + args))]
Guido van Rossum80f8be81997-12-02 19:51:39 +00001420
Fredrik Lundh06d28152000-08-09 18:03:12 +00001421 # Support for the "event" command, new in Tk 4.2.
1422 # By Case Roole.
Guido van Rossum80f8be81997-12-02 19:51:39 +00001423
Fredrik Lundh06d28152000-08-09 18:03:12 +00001424 def event_add(self, virtual, *sequences):
1425 """Bind a virtual event VIRTUAL (of the form <<Name>>)
1426 to an event SEQUENCE such that the virtual event is triggered
1427 whenever SEQUENCE occurs."""
1428 args = ('event', 'add', virtual) + sequences
1429 self.tk.call(args)
Guido van Rossumc2966511998-04-10 19:16:10 +00001430
Fredrik Lundh06d28152000-08-09 18:03:12 +00001431 def event_delete(self, virtual, *sequences):
1432 """Unbind a virtual event VIRTUAL from SEQUENCE."""
1433 args = ('event', 'delete', virtual) + sequences
1434 self.tk.call(args)
Guido van Rossumc2966511998-04-10 19:16:10 +00001435
Fredrik Lundh06d28152000-08-09 18:03:12 +00001436 def event_generate(self, sequence, **kw):
1437 """Generate an event SEQUENCE. Additional
1438 keyword arguments specify parameter of the event
1439 (e.g. x, y, rootx, rooty)."""
1440 args = ('event', 'generate', self._w, sequence)
1441 for k, v in kw.items():
1442 args = args + ('-%s' % k, str(v))
1443 self.tk.call(args)
1444
1445 def event_info(self, virtual=None):
1446 """Return a list of all virtual events or the information
1447 about the SEQUENCE bound to the virtual event VIRTUAL."""
1448 return self.tk.splitlist(
1449 self.tk.call('event', 'info', virtual))
1450
1451 # Image related commands
1452
1453 def image_names(self):
1454 """Return a list of all existing image names."""
1455 return self.tk.call('image', 'names')
1456
1457 def image_types(self):
1458 """Return a list of all available image types (e.g. phote bitmap)."""
1459 return self.tk.call('image', 'types')
Guido van Rossumc2966511998-04-10 19:16:10 +00001460
Guido van Rossum80f8be81997-12-02 19:51:39 +00001461
Guido van Rossuma5773dd1995-09-07 19:22:00 +00001462class CallWrapper:
Fredrik Lundh06d28152000-08-09 18:03:12 +00001463 """Internal class. Stores function to call when some user
1464 defined Tcl function is called e.g. after an event occurred."""
1465 def __init__(self, func, subst, widget):
1466 """Store FUNC, SUBST and WIDGET as members."""
1467 self.func = func
1468 self.subst = subst
1469 self.widget = widget
1470 def __call__(self, *args):
1471 """Apply first function SUBST to arguments, than FUNC."""
1472 try:
1473 if self.subst:
Raymond Hettingerff41c482003-04-06 09:01:11 +00001474 args = self.subst(*args)
1475 return self.func(*args)
Andrew Svetloveb0abce2012-12-03 16:13:07 +02001476 except SystemExit:
1477 raise
Fredrik Lundh06d28152000-08-09 18:03:12 +00001478 except:
1479 self.widget._report_exception()
Guido van Rossum18468821994-06-20 07:49:28 +00001480
Guido van Rossume365a591998-05-01 19:48:20 +00001481
Guilherme Polo1fff0082009-08-14 15:05:30 +00001482class XView:
1483 """Mix-in class for querying and changing the horizontal position
1484 of a widget's window."""
1485
1486 def xview(self, *args):
1487 """Query and change the horizontal position of the view."""
1488 res = self.tk.call(self._w, 'xview', *args)
1489 if not args:
1490 return self._getdoubles(res)
1491
1492 def xview_moveto(self, fraction):
1493 """Adjusts the view in the window so that FRACTION of the
1494 total width of the canvas is off-screen to the left."""
1495 self.tk.call(self._w, 'xview', 'moveto', fraction)
1496
1497 def xview_scroll(self, number, what):
1498 """Shift the x-view according to NUMBER which is measured in "units"
1499 or "pages" (WHAT)."""
1500 self.tk.call(self._w, 'xview', 'scroll', number, what)
1501
1502
1503class YView:
1504 """Mix-in class for querying and changing the vertical position
1505 of a widget's window."""
1506
1507 def yview(self, *args):
1508 """Query and change the vertical position of the view."""
1509 res = self.tk.call(self._w, 'yview', *args)
1510 if not args:
1511 return self._getdoubles(res)
1512
1513 def yview_moveto(self, fraction):
1514 """Adjusts the view in the window so that FRACTION of the
1515 total height of the canvas is off-screen to the top."""
1516 self.tk.call(self._w, 'yview', 'moveto', fraction)
1517
1518 def yview_scroll(self, number, what):
1519 """Shift the y-view according to NUMBER which is measured in
1520 "units" or "pages" (WHAT)."""
1521 self.tk.call(self._w, 'yview', 'scroll', number, what)
1522
1523
Guido van Rossum18468821994-06-20 07:49:28 +00001524class Wm:
Fredrik Lundh06d28152000-08-09 18:03:12 +00001525 """Provides functions for the communication with the window manager."""
Raymond Hettingerff41c482003-04-06 09:01:11 +00001526
Fredrik Lundh06d28152000-08-09 18:03:12 +00001527 def wm_aspect(self,
1528 minNumer=None, minDenom=None,
1529 maxNumer=None, maxDenom=None):
1530 """Instruct the window manager to set the aspect ratio (width/height)
1531 of this widget to be between MINNUMER/MINDENOM and MAXNUMER/MAXDENOM. Return a tuple
1532 of the actual values if no argument is given."""
1533 return self._getints(
1534 self.tk.call('wm', 'aspect', self._w,
1535 minNumer, minDenom,
1536 maxNumer, maxDenom))
1537 aspect = wm_aspect
Raymond Hettingerff41c482003-04-06 09:01:11 +00001538
Martin v. Löwis2ec36272002-10-13 10:22:08 +00001539 def wm_attributes(self, *args):
1540 """This subcommand returns or sets platform specific attributes
Raymond Hettingerff41c482003-04-06 09:01:11 +00001541
1542 The first form returns a list of the platform specific flags and
1543 their values. The second form returns the value for the specific
Martin v. Löwis2ec36272002-10-13 10:22:08 +00001544 option. The third form sets one or more of the values. The values
1545 are as follows:
Raymond Hettingerff41c482003-04-06 09:01:11 +00001546
1547 On Windows, -disabled gets or sets whether the window is in a
Martin v. Löwis2ec36272002-10-13 10:22:08 +00001548 disabled state. -toolwindow gets or sets the style of the window
Raymond Hettingerff41c482003-04-06 09:01:11 +00001549 to toolwindow (as defined in the MSDN). -topmost gets or sets
1550 whether this is a topmost window (displays above all other
Martin v. Löwis2ec36272002-10-13 10:22:08 +00001551 windows).
Raymond Hettingerff41c482003-04-06 09:01:11 +00001552
1553 On Macintosh, XXXXX
1554
Martin v. Löwis2ec36272002-10-13 10:22:08 +00001555 On Unix, there are currently no special attribute values.
1556 """
1557 args = ('wm', 'attributes', self._w) + args
1558 return self.tk.call(args)
1559 attributes=wm_attributes
Raymond Hettingerff41c482003-04-06 09:01:11 +00001560
Fredrik Lundh06d28152000-08-09 18:03:12 +00001561 def wm_client(self, name=None):
1562 """Store NAME in WM_CLIENT_MACHINE property of this widget. Return
1563 current value."""
1564 return self.tk.call('wm', 'client', self._w, name)
1565 client = wm_client
1566 def wm_colormapwindows(self, *wlist):
1567 """Store list of window names (WLIST) into WM_COLORMAPWINDOWS property
1568 of this widget. This list contains windows whose colormaps differ from their
1569 parents. Return current list of widgets if WLIST is empty."""
1570 if len(wlist) > 1:
1571 wlist = (wlist,) # Tk needs a list of windows here
1572 args = ('wm', 'colormapwindows', self._w) + wlist
Alexander Belopolsky022f0492010-11-22 19:40:51 +00001573 return [self._nametowidget(x) for x in self.tk.call(args)]
Fredrik Lundh06d28152000-08-09 18:03:12 +00001574 colormapwindows = wm_colormapwindows
1575 def wm_command(self, value=None):
1576 """Store VALUE in WM_COMMAND property. It is the command
1577 which shall be used to invoke the application. Return current
1578 command if VALUE is None."""
1579 return self.tk.call('wm', 'command', self._w, value)
1580 command = wm_command
1581 def wm_deiconify(self):
1582 """Deiconify this widget. If it was never mapped it will not be mapped.
1583 On Windows it will raise this widget and give it the focus."""
1584 return self.tk.call('wm', 'deiconify', self._w)
1585 deiconify = wm_deiconify
1586 def wm_focusmodel(self, model=None):
1587 """Set focus model to MODEL. "active" means that this widget will claim
1588 the focus itself, "passive" means that the window manager shall give
1589 the focus. Return current focus model if MODEL is None."""
1590 return self.tk.call('wm', 'focusmodel', self._w, model)
1591 focusmodel = wm_focusmodel
Martin v. Löwis5c3c4242012-03-13 13:40:42 -07001592 def wm_forget(self, window): # new in Tk 8.5
1593 """The window will be unmappend from the screen and will no longer
1594 be managed by wm. toplevel windows will be treated like frame
1595 windows once they are no longer managed by wm, however, the menu
1596 option configuration will be remembered and the menus will return
1597 once the widget is managed again."""
1598 self.tk.call('wm', 'forget', window)
1599 forget = wm_forget
Fredrik Lundh06d28152000-08-09 18:03:12 +00001600 def wm_frame(self):
1601 """Return identifier for decorative frame of this widget if present."""
1602 return self.tk.call('wm', 'frame', self._w)
1603 frame = wm_frame
1604 def wm_geometry(self, newGeometry=None):
1605 """Set geometry to NEWGEOMETRY of the form =widthxheight+x+y. Return
1606 current value if None is given."""
1607 return self.tk.call('wm', 'geometry', self._w, newGeometry)
1608 geometry = wm_geometry
1609 def wm_grid(self,
1610 baseWidth=None, baseHeight=None,
1611 widthInc=None, heightInc=None):
1612 """Instruct the window manager that this widget shall only be
1613 resized on grid boundaries. WIDTHINC and HEIGHTINC are the width and
1614 height of a grid unit in pixels. BASEWIDTH and BASEHEIGHT are the
1615 number of grid units requested in Tk_GeometryRequest."""
1616 return self._getints(self.tk.call(
1617 'wm', 'grid', self._w,
1618 baseWidth, baseHeight, widthInc, heightInc))
1619 grid = wm_grid
1620 def wm_group(self, pathName=None):
1621 """Set the group leader widgets for related widgets to PATHNAME. Return
1622 the group leader of this widget if None is given."""
1623 return self.tk.call('wm', 'group', self._w, pathName)
1624 group = wm_group
Thomas Wouters0e3f5912006-08-11 14:57:12 +00001625 def wm_iconbitmap(self, bitmap=None, default=None):
Fredrik Lundh06d28152000-08-09 18:03:12 +00001626 """Set bitmap for the iconified widget to BITMAP. Return
Thomas Wouters0e3f5912006-08-11 14:57:12 +00001627 the bitmap if None is given.
1628
1629 Under Windows, the DEFAULT parameter can be used to set the icon
1630 for the widget and any descendents that don't have an icon set
1631 explicitly. DEFAULT can be the relative path to a .ico file
1632 (example: root.iconbitmap(default='myicon.ico') ). See Tk
1633 documentation for more information."""
1634 if default:
1635 return self.tk.call('wm', 'iconbitmap', self._w, '-default', default)
1636 else:
1637 return self.tk.call('wm', 'iconbitmap', self._w, bitmap)
Fredrik Lundh06d28152000-08-09 18:03:12 +00001638 iconbitmap = wm_iconbitmap
1639 def wm_iconify(self):
1640 """Display widget as icon."""
1641 return self.tk.call('wm', 'iconify', self._w)
1642 iconify = wm_iconify
1643 def wm_iconmask(self, bitmap=None):
1644 """Set mask for the icon bitmap of this widget. Return the
1645 mask if None is given."""
1646 return self.tk.call('wm', 'iconmask', self._w, bitmap)
1647 iconmask = wm_iconmask
1648 def wm_iconname(self, newName=None):
1649 """Set the name of the icon for this widget. Return the name if
1650 None is given."""
1651 return self.tk.call('wm', 'iconname', self._w, newName)
1652 iconname = wm_iconname
Martin v. Löwis5c3c4242012-03-13 13:40:42 -07001653 def wm_iconphoto(self, default=False, *args): # new in Tk 8.5
1654 """Sets the titlebar icon for this window based on the named photo
1655 images passed through args. If default is True, this is applied to
1656 all future created toplevels as well.
1657
1658 The data in the images is taken as a snapshot at the time of
1659 invocation. If the images are later changed, this is not reflected
1660 to the titlebar icons. Multiple images are accepted to allow
1661 different images sizes to be provided. The window manager may scale
1662 provided icons to an appropriate size.
1663
1664 On Windows, the images are packed into a Windows icon structure.
1665 This will override an icon specified to wm_iconbitmap, and vice
1666 versa.
1667
1668 On X, the images are arranged into the _NET_WM_ICON X property,
1669 which most modern window managers support. An icon specified by
1670 wm_iconbitmap may exist simuultaneously.
1671
1672 On Macintosh, this currently does nothing."""
1673 if default:
1674 self.tk.call('wm', 'iconphoto', self._w, "-default", *args)
1675 else:
1676 self.tk.call('wm', 'iconphoto', self._w, *args)
1677 iconphoto = wm_iconphoto
Fredrik Lundh06d28152000-08-09 18:03:12 +00001678 def wm_iconposition(self, x=None, y=None):
1679 """Set the position of the icon of this widget to X and Y. Return
1680 a tuple of the current values of X and X if None is given."""
1681 return self._getints(self.tk.call(
1682 'wm', 'iconposition', self._w, x, y))
1683 iconposition = wm_iconposition
1684 def wm_iconwindow(self, pathName=None):
1685 """Set widget PATHNAME to be displayed instead of icon. Return the current
1686 value if None is given."""
1687 return self.tk.call('wm', 'iconwindow', self._w, pathName)
1688 iconwindow = wm_iconwindow
Martin v. Löwis5c3c4242012-03-13 13:40:42 -07001689 def wm_manage(self, widget): # new in Tk 8.5
1690 """The widget specified will become a stand alone top-level window.
1691 The window will be decorated with the window managers title bar,
1692 etc."""
1693 self.tk.call('wm', 'manage', widget)
1694 manage = wm_manage
Fredrik Lundh06d28152000-08-09 18:03:12 +00001695 def wm_maxsize(self, width=None, height=None):
1696 """Set max WIDTH and HEIGHT for this widget. If the window is gridded
1697 the values are given in grid units. Return the current values if None
1698 is given."""
1699 return self._getints(self.tk.call(
1700 'wm', 'maxsize', self._w, width, height))
1701 maxsize = wm_maxsize
1702 def wm_minsize(self, width=None, height=None):
1703 """Set min WIDTH and HEIGHT for this widget. If the window is gridded
1704 the values are given in grid units. Return the current values if None
1705 is given."""
1706 return self._getints(self.tk.call(
1707 'wm', 'minsize', self._w, width, height))
1708 minsize = wm_minsize
1709 def wm_overrideredirect(self, boolean=None):
1710 """Instruct the window manager to ignore this widget
1711 if BOOLEAN is given with 1. Return the current value if None
1712 is given."""
1713 return self._getboolean(self.tk.call(
1714 'wm', 'overrideredirect', self._w, boolean))
1715 overrideredirect = wm_overrideredirect
1716 def wm_positionfrom(self, who=None):
1717 """Instruct the window manager that the position of this widget shall
1718 be defined by the user if WHO is "user", and by its own policy if WHO is
1719 "program"."""
1720 return self.tk.call('wm', 'positionfrom', self._w, who)
1721 positionfrom = wm_positionfrom
1722 def wm_protocol(self, name=None, func=None):
1723 """Bind function FUNC to command NAME for this widget.
1724 Return the function bound to NAME if None is given. NAME could be
1725 e.g. "WM_SAVE_YOURSELF" or "WM_DELETE_WINDOW"."""
Florent Xicluna5d1155c2011-10-28 14:45:05 +02001726 if callable(func):
Fredrik Lundh06d28152000-08-09 18:03:12 +00001727 command = self._register(func)
1728 else:
1729 command = func
1730 return self.tk.call(
1731 'wm', 'protocol', self._w, name, command)
1732 protocol = wm_protocol
1733 def wm_resizable(self, width=None, height=None):
1734 """Instruct the window manager whether this width can be resized
1735 in WIDTH or HEIGHT. Both values are boolean values."""
1736 return self.tk.call('wm', 'resizable', self._w, width, height)
1737 resizable = wm_resizable
1738 def wm_sizefrom(self, who=None):
1739 """Instruct the window manager that the size of this widget shall
1740 be defined by the user if WHO is "user", and by its own policy if WHO is
1741 "program"."""
1742 return self.tk.call('wm', 'sizefrom', self._w, who)
1743 sizefrom = wm_sizefrom
Fredrik Lundh289ad8f2000-08-09 19:11:59 +00001744 def wm_state(self, newstate=None):
1745 """Query or set the state of this widget as one of normal, icon,
1746 iconic (see wm_iconwindow), withdrawn, or zoomed (Windows only)."""
1747 return self.tk.call('wm', 'state', self._w, newstate)
Fredrik Lundh06d28152000-08-09 18:03:12 +00001748 state = wm_state
1749 def wm_title(self, string=None):
1750 """Set the title of this widget."""
1751 return self.tk.call('wm', 'title', self._w, string)
1752 title = wm_title
1753 def wm_transient(self, master=None):
1754 """Instruct the window manager that this widget is transient
1755 with regard to widget MASTER."""
1756 return self.tk.call('wm', 'transient', self._w, master)
1757 transient = wm_transient
1758 def wm_withdraw(self):
1759 """Withdraw this widget from the screen such that it is unmapped
1760 and forgotten by the window manager. Re-draw it with wm_deiconify."""
1761 return self.tk.call('wm', 'withdraw', self._w)
1762 withdraw = wm_withdraw
Guido van Rossume365a591998-05-01 19:48:20 +00001763
Guido van Rossum18468821994-06-20 07:49:28 +00001764
1765class Tk(Misc, Wm):
Fredrik Lundh06d28152000-08-09 18:03:12 +00001766 """Toplevel widget of Tk which represents mostly the main window
Ezio Melotti42da6632011-03-15 05:18:48 +02001767 of an application. It has an associated Tcl interpreter."""
Fredrik Lundh06d28152000-08-09 18:03:12 +00001768 _w = '.'
Martin v. Löwis9441c072004-08-03 18:36:25 +00001769 def __init__(self, screenName=None, baseName=None, className='Tk',
1770 useTk=1, sync=0, use=None):
Fredrik Lundh06d28152000-08-09 18:03:12 +00001771 """Return a new Toplevel widget on screen SCREENNAME. A new Tcl interpreter will
1772 be created. BASENAME will be used for the identification of the profile file (see
1773 readprofile).
1774 It is constructed from sys.argv[0] without extensions if None is given. CLASSNAME
1775 is the name of the widget class."""
Fredrik Lundh06d28152000-08-09 18:03:12 +00001776 self.master = None
1777 self.children = {}
David Aschere2b4b322004-02-18 05:59:53 +00001778 self._tkloaded = 0
1779 # to avoid recursions in the getattr code in case of failure, we
1780 # ensure that self.tk is always _something_.
Tim Peters182b5ac2004-07-18 06:16:08 +00001781 self.tk = None
Fredrik Lundh06d28152000-08-09 18:03:12 +00001782 if baseName is None:
Florent Xicluna54540ec2011-11-04 08:29:17 +01001783 import os
Fredrik Lundh06d28152000-08-09 18:03:12 +00001784 baseName = os.path.basename(sys.argv[0])
1785 baseName, ext = os.path.splitext(baseName)
1786 if ext not in ('.py', '.pyc', '.pyo'):
1787 baseName = baseName + ext
David Aschere2b4b322004-02-18 05:59:53 +00001788 interactive = 0
Martin v. Löwis9441c072004-08-03 18:36:25 +00001789 self.tk = _tkinter.create(screenName, baseName, className, interactive, wantobjects, useTk, sync, use)
David Aschere2b4b322004-02-18 05:59:53 +00001790 if useTk:
1791 self._loadtk()
Antoine Pitrou7ec3a322012-12-09 14:46:18 +01001792 if not sys.flags.ignore_environment:
1793 # Issue #16248: Honor the -E flag to avoid code injection.
1794 self.readprofile(baseName, className)
David Aschere2b4b322004-02-18 05:59:53 +00001795 def loadtk(self):
1796 if not self._tkloaded:
1797 self.tk.loadtk()
1798 self._loadtk()
1799 def _loadtk(self):
1800 self._tkloaded = 1
1801 global _default_root
Fredrik Lundh06d28152000-08-09 18:03:12 +00001802 # Version sanity checks
1803 tk_version = self.tk.getvar('tk_version')
1804 if tk_version != _tkinter.TK_VERSION:
Collin Winterce36ad82007-08-30 01:19:48 +00001805 raise RuntimeError("tk.h version (%s) doesn't match libtk.a version (%s)"
1806 % (_tkinter.TK_VERSION, tk_version))
Martin v. Löwis54895972003-05-24 11:37:15 +00001807 # Under unknown circumstances, tcl_version gets coerced to float
1808 tcl_version = str(self.tk.getvar('tcl_version'))
Fredrik Lundh06d28152000-08-09 18:03:12 +00001809 if tcl_version != _tkinter.TCL_VERSION:
Collin Winterce36ad82007-08-30 01:19:48 +00001810 raise RuntimeError("tcl.h version (%s) doesn't match libtcl.a version (%s)" \
1811 % (_tkinter.TCL_VERSION, tcl_version))
Fredrik Lundh06d28152000-08-09 18:03:12 +00001812 if TkVersion < 4.0:
Collin Winterce36ad82007-08-30 01:19:48 +00001813 raise RuntimeError("Tk 4.0 or higher is required; found Tk %s"
1814 % str(TkVersion))
Martin v. Löwis4afe1542005-03-01 08:09:28 +00001815 # Create and register the tkerror and exit commands
1816 # We need to inline parts of _register here, _ register
1817 # would register differently-named commands.
1818 if self._tclCommands is None:
1819 self._tclCommands = []
Fredrik Lundh06d28152000-08-09 18:03:12 +00001820 self.tk.createcommand('tkerror', _tkerror)
1821 self.tk.createcommand('exit', _exit)
Martin v. Löwis4afe1542005-03-01 08:09:28 +00001822 self._tclCommands.append('tkerror')
1823 self._tclCommands.append('exit')
Fredrik Lundh06d28152000-08-09 18:03:12 +00001824 if _support_default_root and not _default_root:
1825 _default_root = self
1826 self.protocol("WM_DELETE_WINDOW", self.destroy)
1827 def destroy(self):
1828 """Destroy this and all descendants widgets. This will
1829 end the application of this Tcl interpreter."""
Guido van Rossumb5a755e2007-07-18 18:15:48 +00001830 for c in list(self.children.values()): c.destroy()
Fredrik Lundh06d28152000-08-09 18:03:12 +00001831 self.tk.call('destroy', self._w)
1832 Misc.destroy(self)
1833 global _default_root
1834 if _support_default_root and _default_root is self:
1835 _default_root = None
1836 def readprofile(self, baseName, className):
1837 """Internal function. It reads BASENAME.tcl and CLASSNAME.tcl into
Neal Norwitz01688022007-08-12 00:43:29 +00001838 the Tcl Interpreter and calls exec on the contents of BASENAME.py and
1839 CLASSNAME.py if such a file exists in the home directory."""
Fredrik Lundh06d28152000-08-09 18:03:12 +00001840 import os
Guido van Rossume014a132006-08-19 16:53:45 +00001841 if 'HOME' in os.environ: home = os.environ['HOME']
Fredrik Lundh06d28152000-08-09 18:03:12 +00001842 else: home = os.curdir
1843 class_tcl = os.path.join(home, '.%s.tcl' % className)
1844 class_py = os.path.join(home, '.%s.py' % className)
1845 base_tcl = os.path.join(home, '.%s.tcl' % baseName)
1846 base_py = os.path.join(home, '.%s.py' % baseName)
1847 dir = {'self': self}
Georg Brandl14fc4272008-05-17 18:39:55 +00001848 exec('from tkinter import *', dir)
Fredrik Lundh06d28152000-08-09 18:03:12 +00001849 if os.path.isfile(class_tcl):
Fredrik Lundh06d28152000-08-09 18:03:12 +00001850 self.tk.call('source', class_tcl)
1851 if os.path.isfile(class_py):
Neal Norwitz01688022007-08-12 00:43:29 +00001852 exec(open(class_py).read(), dir)
Fredrik Lundh06d28152000-08-09 18:03:12 +00001853 if os.path.isfile(base_tcl):
Fredrik Lundh06d28152000-08-09 18:03:12 +00001854 self.tk.call('source', base_tcl)
1855 if os.path.isfile(base_py):
Neal Norwitz01688022007-08-12 00:43:29 +00001856 exec(open(base_py).read(), dir)
Fredrik Lundh06d28152000-08-09 18:03:12 +00001857 def report_callback_exception(self, exc, val, tb):
1858 """Internal function. It reports exception on sys.stderr."""
Florent Xicluna54540ec2011-11-04 08:29:17 +01001859 import traceback
Fredrik Lundh06d28152000-08-09 18:03:12 +00001860 sys.stderr.write("Exception in Tkinter callback\n")
1861 sys.last_type = exc
1862 sys.last_value = val
1863 sys.last_traceback = tb
1864 traceback.print_exception(exc, val, tb)
David Aschere2b4b322004-02-18 05:59:53 +00001865 def __getattr__(self, attr):
1866 "Delegate attribute access to the interpreter object"
1867 return getattr(self.tk, attr)
Guido van Rossum18468821994-06-20 07:49:28 +00001868
Guido van Rossum368e06b1997-11-07 20:38:49 +00001869# Ideally, the classes Pack, Place and Grid disappear, the
1870# pack/place/grid methods are defined on the Widget class, and
1871# everybody uses w.pack_whatever(...) instead of Pack.whatever(w,
1872# ...), with pack(), place() and grid() being short for
1873# pack_configure(), place_configure() and grid_columnconfigure(), and
1874# forget() being short for pack_forget(). As a practical matter, I'm
1875# afraid that there is too much code out there that may be using the
1876# Pack, Place or Grid class, so I leave them intact -- but only as
1877# backwards compatibility features. Also note that those methods that
1878# take a master as argument (e.g. pack_propagate) have been moved to
1879# the Misc class (which now incorporates all methods common between
1880# toplevel and interior widgets). Again, for compatibility, these are
1881# copied into the Pack, Place or Grid class.
1882
David Aschere2b4b322004-02-18 05:59:53 +00001883
1884def Tcl(screenName=None, baseName=None, className='Tk', useTk=0):
1885 return Tk(screenName, baseName, className, useTk)
1886
Guido van Rossum18468821994-06-20 07:49:28 +00001887class Pack:
Fredrik Lundh06d28152000-08-09 18:03:12 +00001888 """Geometry manager Pack.
Guido van Rossum5917ecb2000-06-29 16:30:50 +00001889
Fredrik Lundh06d28152000-08-09 18:03:12 +00001890 Base class to use the methods pack_* in every widget."""
1891 def pack_configure(self, cnf={}, **kw):
1892 """Pack a widget in the parent widget. Use as options:
1893 after=widget - pack it after you have packed widget
1894 anchor=NSEW (or subset) - position widget according to
1895 given direction
Georg Brandlbf1eb632008-05-29 07:19:00 +00001896 before=widget - pack it before you will pack widget
Martin v. Löwisbfe175c2003-04-16 19:42:51 +00001897 expand=bool - expand widget if parent size grows
Fredrik Lundh06d28152000-08-09 18:03:12 +00001898 fill=NONE or X or Y or BOTH - fill widget if widget grows
1899 in=master - use master to contain this widget
Georg Brandlbf1eb632008-05-29 07:19:00 +00001900 in_=master - see 'in' option description
Fredrik Lundh06d28152000-08-09 18:03:12 +00001901 ipadx=amount - add internal padding in x direction
1902 ipady=amount - add internal padding in y direction
1903 padx=amount - add padding in x direction
1904 pady=amount - add padding in y direction
1905 side=TOP or BOTTOM or LEFT or RIGHT - where to add this widget.
1906 """
1907 self.tk.call(
1908 ('pack', 'configure', self._w)
1909 + self._options(cnf, kw))
1910 pack = configure = config = pack_configure
1911 def pack_forget(self):
1912 """Unmap this widget and do not use it for the packing order."""
1913 self.tk.call('pack', 'forget', self._w)
1914 forget = pack_forget
1915 def pack_info(self):
1916 """Return information about the packing options
1917 for this widget."""
1918 words = self.tk.splitlist(
1919 self.tk.call('pack', 'info', self._w))
1920 dict = {}
1921 for i in range(0, len(words), 2):
1922 key = words[i][1:]
1923 value = words[i+1]
1924 if value[:1] == '.':
1925 value = self._nametowidget(value)
1926 dict[key] = value
1927 return dict
1928 info = pack_info
1929 propagate = pack_propagate = Misc.pack_propagate
1930 slaves = pack_slaves = Misc.pack_slaves
Guido van Rossum18468821994-06-20 07:49:28 +00001931
1932class Place:
Fredrik Lundh06d28152000-08-09 18:03:12 +00001933 """Geometry manager Place.
Guido van Rossum5917ecb2000-06-29 16:30:50 +00001934
Fredrik Lundh06d28152000-08-09 18:03:12 +00001935 Base class to use the methods place_* in every widget."""
1936 def place_configure(self, cnf={}, **kw):
1937 """Place a widget in the parent widget. Use as options:
Georg Brandlbf1eb632008-05-29 07:19:00 +00001938 in=master - master relative to which the widget is placed
1939 in_=master - see 'in' option description
Fredrik Lundh06d28152000-08-09 18:03:12 +00001940 x=amount - locate anchor of this widget at position x of master
1941 y=amount - locate anchor of this widget at position y of master
1942 relx=amount - locate anchor of this widget between 0.0 and 1.0
1943 relative to width of master (1.0 is right edge)
Georg Brandlbf1eb632008-05-29 07:19:00 +00001944 rely=amount - locate anchor of this widget between 0.0 and 1.0
Fredrik Lundh06d28152000-08-09 18:03:12 +00001945 relative to height of master (1.0 is bottom edge)
Georg Brandlbf1eb632008-05-29 07:19:00 +00001946 anchor=NSEW (or subset) - position anchor according to given direction
Fredrik Lundh06d28152000-08-09 18:03:12 +00001947 width=amount - width of this widget in pixel
1948 height=amount - height of this widget in pixel
1949 relwidth=amount - width of this widget between 0.0 and 1.0
1950 relative to width of master (1.0 is the same width
Georg Brandlbf1eb632008-05-29 07:19:00 +00001951 as the master)
1952 relheight=amount - height of this widget between 0.0 and 1.0
Fredrik Lundh06d28152000-08-09 18:03:12 +00001953 relative to height of master (1.0 is the same
Georg Brandlbf1eb632008-05-29 07:19:00 +00001954 height as the master)
1955 bordermode="inside" or "outside" - whether to take border width of
1956 master widget into account
1957 """
Fredrik Lundh06d28152000-08-09 18:03:12 +00001958 self.tk.call(
1959 ('place', 'configure', self._w)
1960 + self._options(cnf, kw))
1961 place = configure = config = place_configure
1962 def place_forget(self):
1963 """Unmap this widget."""
1964 self.tk.call('place', 'forget', self._w)
1965 forget = place_forget
1966 def place_info(self):
1967 """Return information about the placing options
1968 for this widget."""
1969 words = self.tk.splitlist(
1970 self.tk.call('place', 'info', self._w))
1971 dict = {}
1972 for i in range(0, len(words), 2):
1973 key = words[i][1:]
1974 value = words[i+1]
1975 if value[:1] == '.':
1976 value = self._nametowidget(value)
1977 dict[key] = value
1978 return dict
1979 info = place_info
1980 slaves = place_slaves = Misc.place_slaves
Guido van Rossum18468821994-06-20 07:49:28 +00001981
Guido van Rossum37dcab11996-05-16 16:00:19 +00001982class Grid:
Fredrik Lundh06d28152000-08-09 18:03:12 +00001983 """Geometry manager Grid.
Guido van Rossum5917ecb2000-06-29 16:30:50 +00001984
Fredrik Lundh06d28152000-08-09 18:03:12 +00001985 Base class to use the methods grid_* in every widget."""
1986 # Thanks to Masazumi Yoshikawa (yosikawa@isi.edu)
1987 def grid_configure(self, cnf={}, **kw):
1988 """Position a widget in the parent widget in a grid. Use as options:
1989 column=number - use cell identified with given column (starting with 0)
1990 columnspan=number - this widget will span several columns
1991 in=master - use master to contain this widget
Georg Brandlbf1eb632008-05-29 07:19:00 +00001992 in_=master - see 'in' option description
Fredrik Lundh06d28152000-08-09 18:03:12 +00001993 ipadx=amount - add internal padding in x direction
1994 ipady=amount - add internal padding in y direction
1995 padx=amount - add padding in x direction
1996 pady=amount - add padding in y direction
1997 row=number - use cell identified with given row (starting with 0)
1998 rowspan=number - this widget will span several rows
1999 sticky=NSEW - if cell is larger on which sides will this
2000 widget stick to the cell boundary
2001 """
2002 self.tk.call(
2003 ('grid', 'configure', self._w)
2004 + self._options(cnf, kw))
2005 grid = configure = config = grid_configure
2006 bbox = grid_bbox = Misc.grid_bbox
2007 columnconfigure = grid_columnconfigure = Misc.grid_columnconfigure
2008 def grid_forget(self):
2009 """Unmap this widget."""
2010 self.tk.call('grid', 'forget', self._w)
2011 forget = grid_forget
2012 def grid_remove(self):
2013 """Unmap this widget but remember the grid options."""
2014 self.tk.call('grid', 'remove', self._w)
2015 def grid_info(self):
2016 """Return information about the options
2017 for positioning this widget in a grid."""
2018 words = self.tk.splitlist(
2019 self.tk.call('grid', 'info', self._w))
2020 dict = {}
2021 for i in range(0, len(words), 2):
2022 key = words[i][1:]
2023 value = words[i+1]
2024 if value[:1] == '.':
2025 value = self._nametowidget(value)
2026 dict[key] = value
2027 return dict
2028 info = grid_info
Martin v. Löwisdc579092001-10-13 09:33:51 +00002029 location = grid_location = Misc.grid_location
Fredrik Lundh06d28152000-08-09 18:03:12 +00002030 propagate = grid_propagate = Misc.grid_propagate
2031 rowconfigure = grid_rowconfigure = Misc.grid_rowconfigure
2032 size = grid_size = Misc.grid_size
2033 slaves = grid_slaves = Misc.grid_slaves
Guido van Rossum37dcab11996-05-16 16:00:19 +00002034
Guido van Rossum368e06b1997-11-07 20:38:49 +00002035class BaseWidget(Misc):
Fredrik Lundh06d28152000-08-09 18:03:12 +00002036 """Internal class."""
2037 def _setup(self, master, cnf):
2038 """Internal function. Sets up information about children."""
2039 if _support_default_root:
2040 global _default_root
2041 if not master:
2042 if not _default_root:
2043 _default_root = Tk()
2044 master = _default_root
2045 self.master = master
2046 self.tk = master.tk
2047 name = None
Guido van Rossume014a132006-08-19 16:53:45 +00002048 if 'name' in cnf:
Fredrik Lundh06d28152000-08-09 18:03:12 +00002049 name = cnf['name']
2050 del cnf['name']
2051 if not name:
Walter Dörwald70a6b492004-02-12 17:35:32 +00002052 name = repr(id(self))
Fredrik Lundh06d28152000-08-09 18:03:12 +00002053 self._name = name
2054 if master._w=='.':
2055 self._w = '.' + name
2056 else:
2057 self._w = master._w + '.' + name
2058 self.children = {}
Guido van Rossume014a132006-08-19 16:53:45 +00002059 if self._name in self.master.children:
Fredrik Lundh06d28152000-08-09 18:03:12 +00002060 self.master.children[self._name].destroy()
2061 self.master.children[self._name] = self
2062 def __init__(self, master, widgetName, cnf={}, kw={}, extra=()):
2063 """Construct a widget with the parent widget MASTER, a name WIDGETNAME
2064 and appropriate options."""
2065 if kw:
2066 cnf = _cnfmerge((cnf, kw))
2067 self.widgetName = widgetName
2068 BaseWidget._setup(self, master, cnf)
Hirokazu Yamamotoa18424c2008-11-04 06:26:27 +00002069 if self._tclCommands is None:
2070 self._tclCommands = []
Guilherme Polob212b752008-09-04 11:21:31 +00002071 classes = [(k, v) for k, v in cnf.items() if isinstance(k, type)]
2072 for k, v in classes:
2073 del cnf[k]
Fredrik Lundh06d28152000-08-09 18:03:12 +00002074 self.tk.call(
2075 (widgetName, self._w) + extra + self._options(cnf))
2076 for k, v in classes:
2077 k.configure(self, v)
2078 def destroy(self):
2079 """Destroy this and all descendants widgets."""
Guido van Rossum992d4a32007-07-11 13:09:30 +00002080 for c in list(self.children.values()): c.destroy()
Thomas Wouters0e3f5912006-08-11 14:57:12 +00002081 self.tk.call('destroy', self._w)
Guido van Rossume014a132006-08-19 16:53:45 +00002082 if self._name in self.master.children:
Fredrik Lundh06d28152000-08-09 18:03:12 +00002083 del self.master.children[self._name]
Fredrik Lundh06d28152000-08-09 18:03:12 +00002084 Misc.destroy(self)
2085 def _do(self, name, args=()):
2086 # XXX Obsolete -- better use self.tk.call directly!
2087 return self.tk.call((self._w, name) + args)
Guido van Rossum18468821994-06-20 07:49:28 +00002088
Guido van Rossum368e06b1997-11-07 20:38:49 +00002089class Widget(BaseWidget, Pack, Place, Grid):
Fredrik Lundh06d28152000-08-09 18:03:12 +00002090 """Internal class.
Guido van Rossum5917ecb2000-06-29 16:30:50 +00002091
Fredrik Lundh06d28152000-08-09 18:03:12 +00002092 Base class for a widget which can be positioned with the geometry managers
2093 Pack, Place or Grid."""
2094 pass
Guido van Rossum368e06b1997-11-07 20:38:49 +00002095
2096class Toplevel(BaseWidget, Wm):
Fredrik Lundh06d28152000-08-09 18:03:12 +00002097 """Toplevel widget, e.g. for dialogs."""
2098 def __init__(self, master=None, cnf={}, **kw):
2099 """Construct a toplevel widget with the parent MASTER.
Guido van Rossum5917ecb2000-06-29 16:30:50 +00002100
Fredrik Lundh06d28152000-08-09 18:03:12 +00002101 Valid resource names: background, bd, bg, borderwidth, class,
2102 colormap, container, cursor, height, highlightbackground,
2103 highlightcolor, highlightthickness, menu, relief, screen, takefocus,
2104 use, visual, width."""
2105 if kw:
2106 cnf = _cnfmerge((cnf, kw))
2107 extra = ()
2108 for wmkey in ['screen', 'class_', 'class', 'visual',
2109 'colormap']:
Guido van Rossume014a132006-08-19 16:53:45 +00002110 if wmkey in cnf:
Fredrik Lundh06d28152000-08-09 18:03:12 +00002111 val = cnf[wmkey]
2112 # TBD: a hack needed because some keys
2113 # are not valid as keyword arguments
2114 if wmkey[-1] == '_': opt = '-'+wmkey[:-1]
2115 else: opt = '-'+wmkey
2116 extra = extra + (opt, val)
2117 del cnf[wmkey]
2118 BaseWidget.__init__(self, master, 'toplevel', cnf, {}, extra)
2119 root = self._root()
2120 self.iconname(root.iconname())
2121 self.title(root.title())
2122 self.protocol("WM_DELETE_WINDOW", self.destroy)
Guido van Rossum18468821994-06-20 07:49:28 +00002123
2124class Button(Widget):
Fredrik Lundh06d28152000-08-09 18:03:12 +00002125 """Button widget."""
2126 def __init__(self, master=None, cnf={}, **kw):
2127 """Construct a button widget with the parent MASTER.
Raymond Hettingerff41c482003-04-06 09:01:11 +00002128
Martin v. Löwis2ec36272002-10-13 10:22:08 +00002129 STANDARD OPTIONS
Raymond Hettingerff41c482003-04-06 09:01:11 +00002130
Martin v. Löwis2ec36272002-10-13 10:22:08 +00002131 activebackground, activeforeground, anchor,
2132 background, bitmap, borderwidth, cursor,
Raymond Hettingerff41c482003-04-06 09:01:11 +00002133 disabledforeground, font, foreground
Martin v. Löwis2ec36272002-10-13 10:22:08 +00002134 highlightbackground, highlightcolor,
Raymond Hettingerff41c482003-04-06 09:01:11 +00002135 highlightthickness, image, justify,
Martin v. Löwis2ec36272002-10-13 10:22:08 +00002136 padx, pady, relief, repeatdelay,
Raymond Hettingerff41c482003-04-06 09:01:11 +00002137 repeatinterval, takefocus, text,
Martin v. Löwis2ec36272002-10-13 10:22:08 +00002138 textvariable, underline, wraplength
Raymond Hettingerff41c482003-04-06 09:01:11 +00002139
Martin v. Löwis2ec36272002-10-13 10:22:08 +00002140 WIDGET-SPECIFIC OPTIONS
Raymond Hettingerff41c482003-04-06 09:01:11 +00002141
Martin v. Löwis2ec36272002-10-13 10:22:08 +00002142 command, compound, default, height,
2143 overrelief, state, width
2144 """
Fredrik Lundh06d28152000-08-09 18:03:12 +00002145 Widget.__init__(self, master, 'button', cnf, kw)
Raymond Hettingerff41c482003-04-06 09:01:11 +00002146
Fredrik Lundh06d28152000-08-09 18:03:12 +00002147 def tkButtonEnter(self, *dummy):
2148 self.tk.call('tkButtonEnter', self._w)
Raymond Hettingerff41c482003-04-06 09:01:11 +00002149
Fredrik Lundh06d28152000-08-09 18:03:12 +00002150 def tkButtonLeave(self, *dummy):
2151 self.tk.call('tkButtonLeave', self._w)
Raymond Hettingerff41c482003-04-06 09:01:11 +00002152
Fredrik Lundh06d28152000-08-09 18:03:12 +00002153 def tkButtonDown(self, *dummy):
2154 self.tk.call('tkButtonDown', self._w)
Raymond Hettingerff41c482003-04-06 09:01:11 +00002155
Fredrik Lundh06d28152000-08-09 18:03:12 +00002156 def tkButtonUp(self, *dummy):
2157 self.tk.call('tkButtonUp', self._w)
Raymond Hettingerff41c482003-04-06 09:01:11 +00002158
Fredrik Lundh06d28152000-08-09 18:03:12 +00002159 def tkButtonInvoke(self, *dummy):
2160 self.tk.call('tkButtonInvoke', self._w)
Raymond Hettingerff41c482003-04-06 09:01:11 +00002161
Fredrik Lundh06d28152000-08-09 18:03:12 +00002162 def flash(self):
Raymond Hettingerff41c482003-04-06 09:01:11 +00002163 """Flash the button.
2164
2165 This is accomplished by redisplaying
2166 the button several times, alternating between active and
2167 normal colors. At the end of the flash the button is left
2168 in the same normal/active state as when the command was
2169 invoked. This command is ignored if the button's state is
Martin v. Löwis2ec36272002-10-13 10:22:08 +00002170 disabled.
2171 """
Fredrik Lundh06d28152000-08-09 18:03:12 +00002172 self.tk.call(self._w, 'flash')
Raymond Hettingerff41c482003-04-06 09:01:11 +00002173
Fredrik Lundh06d28152000-08-09 18:03:12 +00002174 def invoke(self):
Raymond Hettingerff41c482003-04-06 09:01:11 +00002175 """Invoke the command associated with the button.
2176
2177 The return value is the return value from the command,
Martin v. Löwis2ec36272002-10-13 10:22:08 +00002178 or an empty string if there is no command associated with
2179 the button. This command is ignored if the button's state
2180 is disabled.
2181 """
Fredrik Lundh06d28152000-08-09 18:03:12 +00002182 return self.tk.call(self._w, 'invoke')
Guido van Rossum18468821994-06-20 07:49:28 +00002183
Andrew Svetlova966c6f2012-03-21 23:52:59 +02002184
Guido van Rossum18468821994-06-20 07:49:28 +00002185# Indices:
Guido van Rossum35f67fb1995-08-04 03:50:29 +00002186# XXX I don't like these -- take them away
Guido van Rossum18468821994-06-20 07:49:28 +00002187def AtEnd():
Andrew Svetlov69c2ffa2012-03-31 14:55:55 +03002188 warnings.warn("tkinter.AtEnd will be removed in 3.4",
2189 DeprecationWarning, stacklevel=2)
Fredrik Lundh06d28152000-08-09 18:03:12 +00002190 return 'end'
Andrew Svetlova966c6f2012-03-21 23:52:59 +02002191
2192
Guido van Rossum1e9e4001994-06-20 09:09:51 +00002193def AtInsert(*args):
Andrew Svetlov69c2ffa2012-03-31 14:55:55 +03002194 warnings.warn("tkinter.AtInsert will be removed in 3.4",
2195 DeprecationWarning, stacklevel=2)
Fredrik Lundh06d28152000-08-09 18:03:12 +00002196 s = 'insert'
2197 for a in args:
2198 if a: s = s + (' ' + a)
2199 return s
Andrew Svetlova966c6f2012-03-21 23:52:59 +02002200
2201
Guido van Rossum18468821994-06-20 07:49:28 +00002202def AtSelFirst():
Andrew Svetlov69c2ffa2012-03-31 14:55:55 +03002203 warnings.warn("tkinter.AtSelFirst will be removed in 3.4",
2204 DeprecationWarning, stacklevel=2)
Fredrik Lundh06d28152000-08-09 18:03:12 +00002205 return 'sel.first'
Andrew Svetlova966c6f2012-03-21 23:52:59 +02002206
2207
Guido van Rossum18468821994-06-20 07:49:28 +00002208def AtSelLast():
Andrew Svetlov69c2ffa2012-03-31 14:55:55 +03002209 warnings.warn("tkinter.AtSelLast will be removed in 3.4",
2210 DeprecationWarning, stacklevel=2)
Fredrik Lundh06d28152000-08-09 18:03:12 +00002211 return 'sel.last'
Andrew Svetlova966c6f2012-03-21 23:52:59 +02002212
2213
Guido van Rossum18468821994-06-20 07:49:28 +00002214def At(x, y=None):
Andrew Svetlov69c2ffa2012-03-31 14:55:55 +03002215 warnings.warn("tkinter.At will be removed in 3.4",
2216 DeprecationWarning, stacklevel=2)
Fredrik Lundh06d28152000-08-09 18:03:12 +00002217 if y is None:
Walter Dörwald70a6b492004-02-12 17:35:32 +00002218 return '@%r' % (x,)
Fredrik Lundh06d28152000-08-09 18:03:12 +00002219 else:
Walter Dörwald70a6b492004-02-12 17:35:32 +00002220 return '@%r,%r' % (x, y)
Guido van Rossum18468821994-06-20 07:49:28 +00002221
Andrew Svetlova966c6f2012-03-21 23:52:59 +02002222
Guilherme Polo1fff0082009-08-14 15:05:30 +00002223class Canvas(Widget, XView, YView):
Fredrik Lundh06d28152000-08-09 18:03:12 +00002224 """Canvas widget to display graphical elements like lines or text."""
2225 def __init__(self, master=None, cnf={}, **kw):
2226 """Construct a canvas widget with the parent MASTER.
Guido van Rossum5917ecb2000-06-29 16:30:50 +00002227
Fredrik Lundh06d28152000-08-09 18:03:12 +00002228 Valid resource names: background, bd, bg, borderwidth, closeenough,
2229 confine, cursor, height, highlightbackground, highlightcolor,
2230 highlightthickness, insertbackground, insertborderwidth,
2231 insertofftime, insertontime, insertwidth, offset, relief,
2232 scrollregion, selectbackground, selectborderwidth, selectforeground,
2233 state, takefocus, width, xscrollcommand, xscrollincrement,
2234 yscrollcommand, yscrollincrement."""
2235 Widget.__init__(self, master, 'canvas', cnf, kw)
2236 def addtag(self, *args):
2237 """Internal function."""
2238 self.tk.call((self._w, 'addtag') + args)
2239 def addtag_above(self, newtag, tagOrId):
2240 """Add tag NEWTAG to all items above TAGORID."""
2241 self.addtag(newtag, 'above', tagOrId)
2242 def addtag_all(self, newtag):
2243 """Add tag NEWTAG to all items."""
2244 self.addtag(newtag, 'all')
2245 def addtag_below(self, newtag, tagOrId):
2246 """Add tag NEWTAG to all items below TAGORID."""
2247 self.addtag(newtag, 'below', tagOrId)
2248 def addtag_closest(self, newtag, x, y, halo=None, start=None):
2249 """Add tag NEWTAG to item which is closest to pixel at X, Y.
2250 If several match take the top-most.
2251 All items closer than HALO are considered overlapping (all are
2252 closests). If START is specified the next below this tag is taken."""
2253 self.addtag(newtag, 'closest', x, y, halo, start)
2254 def addtag_enclosed(self, newtag, x1, y1, x2, y2):
2255 """Add tag NEWTAG to all items in the rectangle defined
2256 by X1,Y1,X2,Y2."""
2257 self.addtag(newtag, 'enclosed', x1, y1, x2, y2)
2258 def addtag_overlapping(self, newtag, x1, y1, x2, y2):
2259 """Add tag NEWTAG to all items which overlap the rectangle
2260 defined by X1,Y1,X2,Y2."""
2261 self.addtag(newtag, 'overlapping', x1, y1, x2, y2)
2262 def addtag_withtag(self, newtag, tagOrId):
2263 """Add tag NEWTAG to all items with TAGORID."""
2264 self.addtag(newtag, 'withtag', tagOrId)
2265 def bbox(self, *args):
2266 """Return a tuple of X1,Y1,X2,Y2 coordinates for a rectangle
2267 which encloses all items with tags specified as arguments."""
2268 return self._getints(
2269 self.tk.call((self._w, 'bbox') + args)) or None
2270 def tag_unbind(self, tagOrId, sequence, funcid=None):
2271 """Unbind for all items with TAGORID for event SEQUENCE the
2272 function identified with FUNCID."""
2273 self.tk.call(self._w, 'bind', tagOrId, sequence, '')
2274 if funcid:
2275 self.deletecommand(funcid)
2276 def tag_bind(self, tagOrId, sequence=None, func=None, add=None):
2277 """Bind to all items with TAGORID at event SEQUENCE a call to function FUNC.
Guido van Rossum5917ecb2000-06-29 16:30:50 +00002278
Fredrik Lundh06d28152000-08-09 18:03:12 +00002279 An additional boolean parameter ADD specifies whether FUNC will be
2280 called additionally to the other bound function or whether it will
2281 replace the previous function. See bind for the return value."""
2282 return self._bind((self._w, 'bind', tagOrId),
2283 sequence, func, add)
2284 def canvasx(self, screenx, gridspacing=None):
2285 """Return the canvas x coordinate of pixel position SCREENX rounded
2286 to nearest multiple of GRIDSPACING units."""
2287 return getdouble(self.tk.call(
2288 self._w, 'canvasx', screenx, gridspacing))
2289 def canvasy(self, screeny, gridspacing=None):
2290 """Return the canvas y coordinate of pixel position SCREENY rounded
2291 to nearest multiple of GRIDSPACING units."""
2292 return getdouble(self.tk.call(
2293 self._w, 'canvasy', screeny, gridspacing))
2294 def coords(self, *args):
2295 """Return a list of coordinates for the item given in ARGS."""
2296 # XXX Should use _flatten on args
Alexander Belopolsky022f0492010-11-22 19:40:51 +00002297 return [getdouble(x) for x in
Guido van Rossum0bd54331998-05-19 21:18:13 +00002298 self.tk.splitlist(
Alexander Belopolsky022f0492010-11-22 19:40:51 +00002299 self.tk.call((self._w, 'coords') + args))]
Fredrik Lundh06d28152000-08-09 18:03:12 +00002300 def _create(self, itemType, args, kw): # Args: (val, val, ..., cnf={})
2301 """Internal function."""
2302 args = _flatten(args)
2303 cnf = args[-1]
Guido van Rossum13257902007-06-07 23:15:56 +00002304 if isinstance(cnf, (dict, tuple)):
Fredrik Lundh06d28152000-08-09 18:03:12 +00002305 args = args[:-1]
2306 else:
2307 cnf = {}
Raymond Hettingerff41c482003-04-06 09:01:11 +00002308 return getint(self.tk.call(
2309 self._w, 'create', itemType,
2310 *(args + self._options(cnf, kw))))
Fredrik Lundh06d28152000-08-09 18:03:12 +00002311 def create_arc(self, *args, **kw):
2312 """Create arc shaped region with coordinates x1,y1,x2,y2."""
2313 return self._create('arc', args, kw)
2314 def create_bitmap(self, *args, **kw):
2315 """Create bitmap with coordinates x1,y1."""
2316 return self._create('bitmap', args, kw)
2317 def create_image(self, *args, **kw):
2318 """Create image item with coordinates x1,y1."""
2319 return self._create('image', args, kw)
2320 def create_line(self, *args, **kw):
2321 """Create line with coordinates x1,y1,...,xn,yn."""
2322 return self._create('line', args, kw)
2323 def create_oval(self, *args, **kw):
2324 """Create oval with coordinates x1,y1,x2,y2."""
2325 return self._create('oval', args, kw)
2326 def create_polygon(self, *args, **kw):
2327 """Create polygon with coordinates x1,y1,...,xn,yn."""
2328 return self._create('polygon', args, kw)
2329 def create_rectangle(self, *args, **kw):
2330 """Create rectangle with coordinates x1,y1,x2,y2."""
2331 return self._create('rectangle', args, kw)
2332 def create_text(self, *args, **kw):
2333 """Create text with coordinates x1,y1."""
2334 return self._create('text', args, kw)
2335 def create_window(self, *args, **kw):
2336 """Create window with coordinates x1,y1,x2,y2."""
2337 return self._create('window', args, kw)
2338 def dchars(self, *args):
2339 """Delete characters of text items identified by tag or id in ARGS (possibly
2340 several times) from FIRST to LAST character (including)."""
2341 self.tk.call((self._w, 'dchars') + args)
2342 def delete(self, *args):
2343 """Delete items identified by all tag or ids contained in ARGS."""
2344 self.tk.call((self._w, 'delete') + args)
2345 def dtag(self, *args):
2346 """Delete tag or id given as last arguments in ARGS from items
2347 identified by first argument in ARGS."""
2348 self.tk.call((self._w, 'dtag') + args)
2349 def find(self, *args):
2350 """Internal function."""
2351 return self._getints(
2352 self.tk.call((self._w, 'find') + args)) or ()
2353 def find_above(self, tagOrId):
2354 """Return items above TAGORID."""
2355 return self.find('above', tagOrId)
2356 def find_all(self):
2357 """Return all items."""
2358 return self.find('all')
2359 def find_below(self, tagOrId):
2360 """Return all items below TAGORID."""
2361 return self.find('below', tagOrId)
2362 def find_closest(self, x, y, halo=None, start=None):
2363 """Return item which is closest to pixel at X, Y.
2364 If several match take the top-most.
2365 All items closer than HALO are considered overlapping (all are
2366 closests). If START is specified the next below this tag is taken."""
2367 return self.find('closest', x, y, halo, start)
2368 def find_enclosed(self, x1, y1, x2, y2):
2369 """Return all items in rectangle defined
2370 by X1,Y1,X2,Y2."""
2371 return self.find('enclosed', x1, y1, x2, y2)
2372 def find_overlapping(self, x1, y1, x2, y2):
2373 """Return all items which overlap the rectangle
2374 defined by X1,Y1,X2,Y2."""
2375 return self.find('overlapping', x1, y1, x2, y2)
2376 def find_withtag(self, tagOrId):
2377 """Return all items with TAGORID."""
2378 return self.find('withtag', tagOrId)
2379 def focus(self, *args):
2380 """Set focus to the first item specified in ARGS."""
2381 return self.tk.call((self._w, 'focus') + args)
2382 def gettags(self, *args):
2383 """Return tags associated with the first item specified in ARGS."""
2384 return self.tk.splitlist(
2385 self.tk.call((self._w, 'gettags') + args))
2386 def icursor(self, *args):
2387 """Set cursor at position POS in the item identified by TAGORID.
2388 In ARGS TAGORID must be first."""
2389 self.tk.call((self._w, 'icursor') + args)
2390 def index(self, *args):
2391 """Return position of cursor as integer in item specified in ARGS."""
2392 return getint(self.tk.call((self._w, 'index') + args))
2393 def insert(self, *args):
2394 """Insert TEXT in item TAGORID at position POS. ARGS must
2395 be TAGORID POS TEXT."""
2396 self.tk.call((self._w, 'insert') + args)
2397 def itemcget(self, tagOrId, option):
2398 """Return the resource value for an OPTION for item TAGORID."""
2399 return self.tk.call(
2400 (self._w, 'itemcget') + (tagOrId, '-'+option))
2401 def itemconfigure(self, tagOrId, cnf=None, **kw):
2402 """Configure resources of an item TAGORID.
Guido van Rossum5917ecb2000-06-29 16:30:50 +00002403
Fredrik Lundh06d28152000-08-09 18:03:12 +00002404 The values for resources are specified as keyword
2405 arguments. To get an overview about
2406 the allowed keyword arguments call the method without arguments.
2407 """
Martin v. Löwis6ce13152002-10-10 14:36:13 +00002408 return self._configure(('itemconfigure', tagOrId), cnf, kw)
Fredrik Lundh06d28152000-08-09 18:03:12 +00002409 itemconfig = itemconfigure
2410 # lower, tkraise/lift hide Misc.lower, Misc.tkraise/lift,
2411 # so the preferred name for them is tag_lower, tag_raise
2412 # (similar to tag_bind, and similar to the Text widget);
2413 # unfortunately can't delete the old ones yet (maybe in 1.6)
2414 def tag_lower(self, *args):
2415 """Lower an item TAGORID given in ARGS
2416 (optional below another item)."""
2417 self.tk.call((self._w, 'lower') + args)
2418 lower = tag_lower
2419 def move(self, *args):
2420 """Move an item TAGORID given in ARGS."""
2421 self.tk.call((self._w, 'move') + args)
2422 def postscript(self, cnf={}, **kw):
2423 """Print the contents of the canvas to a postscript
2424 file. Valid options: colormap, colormode, file, fontmap,
2425 height, pageanchor, pageheight, pagewidth, pagex, pagey,
2426 rotate, witdh, x, y."""
2427 return self.tk.call((self._w, 'postscript') +
2428 self._options(cnf, kw))
2429 def tag_raise(self, *args):
2430 """Raise an item TAGORID given in ARGS
2431 (optional above another item)."""
2432 self.tk.call((self._w, 'raise') + args)
2433 lift = tkraise = tag_raise
2434 def scale(self, *args):
2435 """Scale item TAGORID with XORIGIN, YORIGIN, XSCALE, YSCALE."""
2436 self.tk.call((self._w, 'scale') + args)
2437 def scan_mark(self, x, y):
2438 """Remember the current X, Y coordinates."""
2439 self.tk.call(self._w, 'scan', 'mark', x, y)
Neal Norwitze931ed52003-01-10 23:24:32 +00002440 def scan_dragto(self, x, y, gain=10):
2441 """Adjust the view of the canvas to GAIN times the
Fredrik Lundh06d28152000-08-09 18:03:12 +00002442 difference between X and Y and the coordinates given in
2443 scan_mark."""
Neal Norwitze931ed52003-01-10 23:24:32 +00002444 self.tk.call(self._w, 'scan', 'dragto', x, y, gain)
Fredrik Lundh06d28152000-08-09 18:03:12 +00002445 def select_adjust(self, tagOrId, index):
2446 """Adjust the end of the selection near the cursor of an item TAGORID to index."""
2447 self.tk.call(self._w, 'select', 'adjust', tagOrId, index)
2448 def select_clear(self):
2449 """Clear the selection if it is in this widget."""
2450 self.tk.call(self._w, 'select', 'clear')
2451 def select_from(self, tagOrId, index):
2452 """Set the fixed end of a selection in item TAGORID to INDEX."""
2453 self.tk.call(self._w, 'select', 'from', tagOrId, index)
2454 def select_item(self):
2455 """Return the item which has the selection."""
Neal Norwitz58b63bf2002-07-23 02:52:58 +00002456 return self.tk.call(self._w, 'select', 'item') or None
Fredrik Lundh06d28152000-08-09 18:03:12 +00002457 def select_to(self, tagOrId, index):
2458 """Set the variable end of a selection in item TAGORID to INDEX."""
2459 self.tk.call(self._w, 'select', 'to', tagOrId, index)
2460 def type(self, tagOrId):
2461 """Return the type of the item TAGORID."""
2462 return self.tk.call(self._w, 'type', tagOrId) or None
Guido van Rossum18468821994-06-20 07:49:28 +00002463
2464class Checkbutton(Widget):
Fredrik Lundh06d28152000-08-09 18:03:12 +00002465 """Checkbutton widget which is either in on- or off-state."""
2466 def __init__(self, master=None, cnf={}, **kw):
2467 """Construct a checkbutton widget with the parent MASTER.
Guido van Rossum5917ecb2000-06-29 16:30:50 +00002468
Fredrik Lundh06d28152000-08-09 18:03:12 +00002469 Valid resource names: activebackground, activeforeground, anchor,
2470 background, bd, bg, bitmap, borderwidth, command, cursor,
2471 disabledforeground, fg, font, foreground, height,
2472 highlightbackground, highlightcolor, highlightthickness, image,
2473 indicatoron, justify, offvalue, onvalue, padx, pady, relief,
2474 selectcolor, selectimage, state, takefocus, text, textvariable,
2475 underline, variable, width, wraplength."""
2476 Widget.__init__(self, master, 'checkbutton', cnf, kw)
2477 def deselect(self):
2478 """Put the button in off-state."""
2479 self.tk.call(self._w, 'deselect')
2480 def flash(self):
2481 """Flash the button."""
2482 self.tk.call(self._w, 'flash')
2483 def invoke(self):
2484 """Toggle the button and invoke a command if given as resource."""
2485 return self.tk.call(self._w, 'invoke')
2486 def select(self):
2487 """Put the button in on-state."""
2488 self.tk.call(self._w, 'select')
2489 def toggle(self):
2490 """Toggle the button."""
2491 self.tk.call(self._w, 'toggle')
Guido van Rossum18468821994-06-20 07:49:28 +00002492
Guilherme Polo1fff0082009-08-14 15:05:30 +00002493class Entry(Widget, XView):
Fredrik Lundh06d28152000-08-09 18:03:12 +00002494 """Entry widget which allows to display simple text."""
2495 def __init__(self, master=None, cnf={}, **kw):
2496 """Construct an entry widget with the parent MASTER.
Guido van Rossum5917ecb2000-06-29 16:30:50 +00002497
Fredrik Lundh06d28152000-08-09 18:03:12 +00002498 Valid resource names: background, bd, bg, borderwidth, cursor,
2499 exportselection, fg, font, foreground, highlightbackground,
2500 highlightcolor, highlightthickness, insertbackground,
2501 insertborderwidth, insertofftime, insertontime, insertwidth,
2502 invalidcommand, invcmd, justify, relief, selectbackground,
2503 selectborderwidth, selectforeground, show, state, takefocus,
2504 textvariable, validate, validatecommand, vcmd, width,
2505 xscrollcommand."""
2506 Widget.__init__(self, master, 'entry', cnf, kw)
2507 def delete(self, first, last=None):
2508 """Delete text from FIRST to LAST (not included)."""
2509 self.tk.call(self._w, 'delete', first, last)
2510 def get(self):
2511 """Return the text."""
2512 return self.tk.call(self._w, 'get')
2513 def icursor(self, index):
2514 """Insert cursor at INDEX."""
2515 self.tk.call(self._w, 'icursor', index)
2516 def index(self, index):
2517 """Return position of cursor."""
2518 return getint(self.tk.call(
2519 self._w, 'index', index))
2520 def insert(self, index, string):
2521 """Insert STRING at INDEX."""
2522 self.tk.call(self._w, 'insert', index, string)
2523 def scan_mark(self, x):
2524 """Remember the current X, Y coordinates."""
2525 self.tk.call(self._w, 'scan', 'mark', x)
2526 def scan_dragto(self, x):
2527 """Adjust the view of the canvas to 10 times the
2528 difference between X and Y and the coordinates given in
2529 scan_mark."""
2530 self.tk.call(self._w, 'scan', 'dragto', x)
2531 def selection_adjust(self, index):
2532 """Adjust the end of the selection near the cursor to INDEX."""
2533 self.tk.call(self._w, 'selection', 'adjust', index)
2534 select_adjust = selection_adjust
2535 def selection_clear(self):
2536 """Clear the selection if it is in this widget."""
2537 self.tk.call(self._w, 'selection', 'clear')
2538 select_clear = selection_clear
2539 def selection_from(self, index):
2540 """Set the fixed end of a selection to INDEX."""
2541 self.tk.call(self._w, 'selection', 'from', index)
2542 select_from = selection_from
2543 def selection_present(self):
Guilherme Polo1fff0082009-08-14 15:05:30 +00002544 """Return True if there are characters selected in the entry, False
2545 otherwise."""
Fredrik Lundh06d28152000-08-09 18:03:12 +00002546 return self.tk.getboolean(
2547 self.tk.call(self._w, 'selection', 'present'))
2548 select_present = selection_present
2549 def selection_range(self, start, end):
2550 """Set the selection from START to END (not included)."""
2551 self.tk.call(self._w, 'selection', 'range', start, end)
2552 select_range = selection_range
2553 def selection_to(self, index):
2554 """Set the variable end of a selection to INDEX."""
2555 self.tk.call(self._w, 'selection', 'to', index)
2556 select_to = selection_to
Guido van Rossum18468821994-06-20 07:49:28 +00002557
2558class Frame(Widget):
Fredrik Lundh06d28152000-08-09 18:03:12 +00002559 """Frame widget which may contain other widgets and can have a 3D border."""
2560 def __init__(self, master=None, cnf={}, **kw):
2561 """Construct a frame widget with the parent MASTER.
Guido van Rossum5917ecb2000-06-29 16:30:50 +00002562
Fredrik Lundh06d28152000-08-09 18:03:12 +00002563 Valid resource names: background, bd, bg, borderwidth, class,
2564 colormap, container, cursor, height, highlightbackground,
2565 highlightcolor, highlightthickness, relief, takefocus, visual, width."""
2566 cnf = _cnfmerge((cnf, kw))
2567 extra = ()
Guido van Rossume014a132006-08-19 16:53:45 +00002568 if 'class_' in cnf:
Fredrik Lundh06d28152000-08-09 18:03:12 +00002569 extra = ('-class', cnf['class_'])
2570 del cnf['class_']
Guido van Rossume014a132006-08-19 16:53:45 +00002571 elif 'class' in cnf:
Fredrik Lundh06d28152000-08-09 18:03:12 +00002572 extra = ('-class', cnf['class'])
2573 del cnf['class']
2574 Widget.__init__(self, master, 'frame', cnf, {}, extra)
Guido van Rossum18468821994-06-20 07:49:28 +00002575
2576class Label(Widget):
Fredrik Lundh06d28152000-08-09 18:03:12 +00002577 """Label widget which can display text and bitmaps."""
2578 def __init__(self, master=None, cnf={}, **kw):
2579 """Construct a label widget with the parent MASTER.
Raymond Hettingerff41c482003-04-06 09:01:11 +00002580
Martin v. Löwis2ec36272002-10-13 10:22:08 +00002581 STANDARD OPTIONS
Raymond Hettingerff41c482003-04-06 09:01:11 +00002582
2583 activebackground, activeforeground, anchor,
2584 background, bitmap, borderwidth, cursor,
Martin v. Löwis2ec36272002-10-13 10:22:08 +00002585 disabledforeground, font, foreground,
Raymond Hettingerff41c482003-04-06 09:01:11 +00002586 highlightbackground, highlightcolor,
2587 highlightthickness, image, justify,
2588 padx, pady, relief, takefocus, text,
Martin v. Löwis2ec36272002-10-13 10:22:08 +00002589 textvariable, underline, wraplength
Raymond Hettingerff41c482003-04-06 09:01:11 +00002590
Martin v. Löwis2ec36272002-10-13 10:22:08 +00002591 WIDGET-SPECIFIC OPTIONS
Raymond Hettingerff41c482003-04-06 09:01:11 +00002592
Martin v. Löwis2ec36272002-10-13 10:22:08 +00002593 height, state, width
Raymond Hettingerff41c482003-04-06 09:01:11 +00002594
Martin v. Löwis2ec36272002-10-13 10:22:08 +00002595 """
Fredrik Lundh06d28152000-08-09 18:03:12 +00002596 Widget.__init__(self, master, 'label', cnf, kw)
Guido van Rossum761c5ab1995-07-14 15:29:10 +00002597
Guilherme Polo1fff0082009-08-14 15:05:30 +00002598class Listbox(Widget, XView, YView):
Fredrik Lundh06d28152000-08-09 18:03:12 +00002599 """Listbox widget which can display a list of strings."""
2600 def __init__(self, master=None, cnf={}, **kw):
2601 """Construct a listbox widget with the parent MASTER.
Guido van Rossum5917ecb2000-06-29 16:30:50 +00002602
Fredrik Lundh06d28152000-08-09 18:03:12 +00002603 Valid resource names: background, bd, bg, borderwidth, cursor,
2604 exportselection, fg, font, foreground, height, highlightbackground,
2605 highlightcolor, highlightthickness, relief, selectbackground,
2606 selectborderwidth, selectforeground, selectmode, setgrid, takefocus,
2607 width, xscrollcommand, yscrollcommand, listvariable."""
2608 Widget.__init__(self, master, 'listbox', cnf, kw)
2609 def activate(self, index):
2610 """Activate item identified by INDEX."""
2611 self.tk.call(self._w, 'activate', index)
2612 def bbox(self, *args):
2613 """Return a tuple of X1,Y1,X2,Y2 coordinates for a rectangle
2614 which encloses the item identified by index in ARGS."""
2615 return self._getints(
2616 self.tk.call((self._w, 'bbox') + args)) or None
2617 def curselection(self):
2618 """Return list of indices of currently selected item."""
2619 # XXX Ought to apply self._getints()...
2620 return self.tk.splitlist(self.tk.call(
2621 self._w, 'curselection'))
2622 def delete(self, first, last=None):
2623 """Delete items from FIRST to LAST (not included)."""
2624 self.tk.call(self._w, 'delete', first, last)
2625 def get(self, first, last=None):
2626 """Get list of items from FIRST to LAST (not included)."""
2627 if last:
2628 return self.tk.splitlist(self.tk.call(
2629 self._w, 'get', first, last))
2630 else:
2631 return self.tk.call(self._w, 'get', first)
2632 def index(self, index):
2633 """Return index of item identified with INDEX."""
2634 i = self.tk.call(self._w, 'index', index)
2635 if i == 'none': return None
2636 return getint(i)
2637 def insert(self, index, *elements):
2638 """Insert ELEMENTS at INDEX."""
2639 self.tk.call((self._w, 'insert', index) + elements)
2640 def nearest(self, y):
2641 """Get index of item which is nearest to y coordinate Y."""
2642 return getint(self.tk.call(
2643 self._w, 'nearest', y))
2644 def scan_mark(self, x, y):
2645 """Remember the current X, Y coordinates."""
2646 self.tk.call(self._w, 'scan', 'mark', x, y)
2647 def scan_dragto(self, x, y):
2648 """Adjust the view of the listbox to 10 times the
2649 difference between X and Y and the coordinates given in
2650 scan_mark."""
2651 self.tk.call(self._w, 'scan', 'dragto', x, y)
2652 def see(self, index):
2653 """Scroll such that INDEX is visible."""
2654 self.tk.call(self._w, 'see', index)
2655 def selection_anchor(self, index):
2656 """Set the fixed end oft the selection to INDEX."""
2657 self.tk.call(self._w, 'selection', 'anchor', index)
2658 select_anchor = selection_anchor
2659 def selection_clear(self, first, last=None):
2660 """Clear the selection from FIRST to LAST (not included)."""
2661 self.tk.call(self._w,
2662 'selection', 'clear', first, last)
2663 select_clear = selection_clear
2664 def selection_includes(self, index):
2665 """Return 1 if INDEX is part of the selection."""
2666 return self.tk.getboolean(self.tk.call(
2667 self._w, 'selection', 'includes', index))
2668 select_includes = selection_includes
2669 def selection_set(self, first, last=None):
2670 """Set the selection from FIRST to LAST (not included) without
2671 changing the currently selected elements."""
2672 self.tk.call(self._w, 'selection', 'set', first, last)
2673 select_set = selection_set
2674 def size(self):
2675 """Return the number of elements in the listbox."""
2676 return getint(self.tk.call(self._w, 'size'))
Guido van Rossum09f1ad82001-09-05 19:29:56 +00002677 def itemcget(self, index, option):
2678 """Return the resource value for an ITEM and an OPTION."""
2679 return self.tk.call(
2680 (self._w, 'itemcget') + (index, '-'+option))
Guido van Rossuma0adb922001-09-01 18:29:55 +00002681 def itemconfigure(self, index, cnf=None, **kw):
Guido van Rossum09f1ad82001-09-05 19:29:56 +00002682 """Configure resources of an ITEM.
Guido van Rossuma0adb922001-09-01 18:29:55 +00002683
2684 The values for resources are specified as keyword arguments.
2685 To get an overview about the allowed keyword arguments
2686 call the method without arguments.
2687 Valid resource names: background, bg, foreground, fg,
2688 selectbackground, selectforeground."""
Martin v. Löwis6ce13152002-10-10 14:36:13 +00002689 return self._configure(('itemconfigure', index), cnf, kw)
Guido van Rossuma0adb922001-09-01 18:29:55 +00002690 itemconfig = itemconfigure
Guido van Rossum18468821994-06-20 07:49:28 +00002691
2692class Menu(Widget):
Fredrik Lundh06d28152000-08-09 18:03:12 +00002693 """Menu widget which allows to display menu bars, pull-down menus and pop-up menus."""
2694 def __init__(self, master=None, cnf={}, **kw):
2695 """Construct menu widget with the parent MASTER.
Guido van Rossum5917ecb2000-06-29 16:30:50 +00002696
Fredrik Lundh06d28152000-08-09 18:03:12 +00002697 Valid resource names: activebackground, activeborderwidth,
2698 activeforeground, background, bd, bg, borderwidth, cursor,
2699 disabledforeground, fg, font, foreground, postcommand, relief,
2700 selectcolor, takefocus, tearoff, tearoffcommand, title, type."""
2701 Widget.__init__(self, master, 'menu', cnf, kw)
2702 def tk_bindForTraversal(self):
2703 pass # obsolete since Tk 4.0
2704 def tk_mbPost(self):
2705 self.tk.call('tk_mbPost', self._w)
2706 def tk_mbUnpost(self):
2707 self.tk.call('tk_mbUnpost')
2708 def tk_traverseToMenu(self, char):
2709 self.tk.call('tk_traverseToMenu', self._w, char)
2710 def tk_traverseWithinMenu(self, char):
2711 self.tk.call('tk_traverseWithinMenu', self._w, char)
2712 def tk_getMenuButtons(self):
2713 return self.tk.call('tk_getMenuButtons', self._w)
2714 def tk_nextMenu(self, count):
2715 self.tk.call('tk_nextMenu', count)
2716 def tk_nextMenuEntry(self, count):
2717 self.tk.call('tk_nextMenuEntry', count)
2718 def tk_invokeMenu(self):
2719 self.tk.call('tk_invokeMenu', self._w)
2720 def tk_firstMenu(self):
2721 self.tk.call('tk_firstMenu', self._w)
2722 def tk_mbButtonDown(self):
2723 self.tk.call('tk_mbButtonDown', self._w)
2724 def tk_popup(self, x, y, entry=""):
2725 """Post the menu at position X,Y with entry ENTRY."""
2726 self.tk.call('tk_popup', self._w, x, y, entry)
2727 def activate(self, index):
2728 """Activate entry at INDEX."""
2729 self.tk.call(self._w, 'activate', index)
2730 def add(self, itemType, cnf={}, **kw):
2731 """Internal function."""
2732 self.tk.call((self._w, 'add', itemType) +
2733 self._options(cnf, kw))
2734 def add_cascade(self, cnf={}, **kw):
2735 """Add hierarchical menu item."""
2736 self.add('cascade', cnf or kw)
2737 def add_checkbutton(self, cnf={}, **kw):
2738 """Add checkbutton menu item."""
2739 self.add('checkbutton', cnf or kw)
2740 def add_command(self, cnf={}, **kw):
2741 """Add command menu item."""
2742 self.add('command', cnf or kw)
2743 def add_radiobutton(self, cnf={}, **kw):
2744 """Addd radio menu item."""
2745 self.add('radiobutton', cnf or kw)
2746 def add_separator(self, cnf={}, **kw):
2747 """Add separator."""
2748 self.add('separator', cnf or kw)
2749 def insert(self, index, itemType, cnf={}, **kw):
2750 """Internal function."""
2751 self.tk.call((self._w, 'insert', index, itemType) +
2752 self._options(cnf, kw))
2753 def insert_cascade(self, index, cnf={}, **kw):
2754 """Add hierarchical menu item at INDEX."""
2755 self.insert(index, 'cascade', cnf or kw)
2756 def insert_checkbutton(self, index, cnf={}, **kw):
2757 """Add checkbutton menu item at INDEX."""
2758 self.insert(index, 'checkbutton', cnf or kw)
2759 def insert_command(self, index, cnf={}, **kw):
2760 """Add command menu item at INDEX."""
2761 self.insert(index, 'command', cnf or kw)
2762 def insert_radiobutton(self, index, cnf={}, **kw):
2763 """Addd radio menu item at INDEX."""
2764 self.insert(index, 'radiobutton', cnf or kw)
2765 def insert_separator(self, index, cnf={}, **kw):
2766 """Add separator at INDEX."""
2767 self.insert(index, 'separator', cnf or kw)
2768 def delete(self, index1, index2=None):
Hirokazu Yamamotoa18424c2008-11-04 06:26:27 +00002769 """Delete menu items between INDEX1 and INDEX2 (included)."""
Robert Schuppenies3d1c7de2008-08-10 11:28:17 +00002770 if index2 is None:
2771 index2 = index1
Robert Schuppenies3d1c7de2008-08-10 11:28:17 +00002772
Hirokazu Yamamotoa18424c2008-11-04 06:26:27 +00002773 num_index1, num_index2 = self.index(index1), self.index(index2)
2774 if (num_index1 is None) or (num_index2 is None):
2775 num_index1, num_index2 = 0, -1
2776
2777 for i in range(num_index1, num_index2 + 1):
2778 if 'command' in self.entryconfig(i):
2779 c = str(self.entrycget(i, 'command'))
2780 if c:
2781 self.deletecommand(c)
2782 self.tk.call(self._w, 'delete', index1, index2)
Fredrik Lundh06d28152000-08-09 18:03:12 +00002783 def entrycget(self, index, option):
2784 """Return the resource value of an menu item for OPTION at INDEX."""
2785 return self.tk.call(self._w, 'entrycget', index, '-' + option)
2786 def entryconfigure(self, index, cnf=None, **kw):
2787 """Configure a menu item at INDEX."""
Martin v. Löwis6ce13152002-10-10 14:36:13 +00002788 return self._configure(('entryconfigure', index), cnf, kw)
Fredrik Lundh06d28152000-08-09 18:03:12 +00002789 entryconfig = entryconfigure
2790 def index(self, index):
2791 """Return the index of a menu item identified by INDEX."""
2792 i = self.tk.call(self._w, 'index', index)
2793 if i == 'none': return None
2794 return getint(i)
2795 def invoke(self, index):
2796 """Invoke a menu item identified by INDEX and execute
2797 the associated command."""
2798 return self.tk.call(self._w, 'invoke', index)
2799 def post(self, x, y):
2800 """Display a menu at position X,Y."""
2801 self.tk.call(self._w, 'post', x, y)
2802 def type(self, index):
2803 """Return the type of the menu item at INDEX."""
2804 return self.tk.call(self._w, 'type', index)
2805 def unpost(self):
2806 """Unmap a menu."""
2807 self.tk.call(self._w, 'unpost')
Martin v. Löwis5c3c4242012-03-13 13:40:42 -07002808 def xposition(self, index): # new in Tk 8.5
2809 """Return the x-position of the leftmost pixel of the menu item
2810 at INDEX."""
2811 return getint(self.tk.call(self._w, 'xposition', index))
Fredrik Lundh06d28152000-08-09 18:03:12 +00002812 def yposition(self, index):
2813 """Return the y-position of the topmost pixel of the menu item at INDEX."""
2814 return getint(self.tk.call(
2815 self._w, 'yposition', index))
Guido van Rossum18468821994-06-20 07:49:28 +00002816
2817class Menubutton(Widget):
Fredrik Lundh06d28152000-08-09 18:03:12 +00002818 """Menubutton widget, obsolete since Tk8.0."""
2819 def __init__(self, master=None, cnf={}, **kw):
2820 Widget.__init__(self, master, 'menubutton', cnf, kw)
Guido van Rossum18468821994-06-20 07:49:28 +00002821
2822class Message(Widget):
Fredrik Lundh06d28152000-08-09 18:03:12 +00002823 """Message widget to display multiline text. Obsolete since Label does it too."""
2824 def __init__(self, master=None, cnf={}, **kw):
2825 Widget.__init__(self, master, 'message', cnf, kw)
Guido van Rossum18468821994-06-20 07:49:28 +00002826
2827class Radiobutton(Widget):
Fredrik Lundh06d28152000-08-09 18:03:12 +00002828 """Radiobutton widget which shows only one of several buttons in on-state."""
2829 def __init__(self, master=None, cnf={}, **kw):
2830 """Construct a radiobutton widget with the parent MASTER.
Guido van Rossum5917ecb2000-06-29 16:30:50 +00002831
Fredrik Lundh06d28152000-08-09 18:03:12 +00002832 Valid resource names: activebackground, activeforeground, anchor,
2833 background, bd, bg, bitmap, borderwidth, command, cursor,
2834 disabledforeground, fg, font, foreground, height,
2835 highlightbackground, highlightcolor, highlightthickness, image,
2836 indicatoron, justify, padx, pady, relief, selectcolor, selectimage,
2837 state, takefocus, text, textvariable, underline, value, variable,
2838 width, wraplength."""
2839 Widget.__init__(self, master, 'radiobutton', cnf, kw)
2840 def deselect(self):
2841 """Put the button in off-state."""
Guido van Rossum5917ecb2000-06-29 16:30:50 +00002842
Fredrik Lundh06d28152000-08-09 18:03:12 +00002843 self.tk.call(self._w, 'deselect')
2844 def flash(self):
2845 """Flash the button."""
2846 self.tk.call(self._w, 'flash')
2847 def invoke(self):
2848 """Toggle the button and invoke a command if given as resource."""
2849 return self.tk.call(self._w, 'invoke')
2850 def select(self):
2851 """Put the button in on-state."""
2852 self.tk.call(self._w, 'select')
Guido van Rossum18468821994-06-20 07:49:28 +00002853
2854class Scale(Widget):
Fredrik Lundh06d28152000-08-09 18:03:12 +00002855 """Scale widget which can display a numerical scale."""
2856 def __init__(self, master=None, cnf={}, **kw):
2857 """Construct a scale widget with the parent MASTER.
Guido van Rossum5917ecb2000-06-29 16:30:50 +00002858
Fredrik Lundh06d28152000-08-09 18:03:12 +00002859 Valid resource names: activebackground, background, bigincrement, bd,
2860 bg, borderwidth, command, cursor, digits, fg, font, foreground, from,
2861 highlightbackground, highlightcolor, highlightthickness, label,
2862 length, orient, relief, repeatdelay, repeatinterval, resolution,
2863 showvalue, sliderlength, sliderrelief, state, takefocus,
2864 tickinterval, to, troughcolor, variable, width."""
2865 Widget.__init__(self, master, 'scale', cnf, kw)
2866 def get(self):
2867 """Get the current value as integer or float."""
2868 value = self.tk.call(self._w, 'get')
2869 try:
2870 return getint(value)
2871 except ValueError:
2872 return getdouble(value)
2873 def set(self, value):
2874 """Set the value to VALUE."""
2875 self.tk.call(self._w, 'set', value)
2876 def coords(self, value=None):
2877 """Return a tuple (X,Y) of the point along the centerline of the
2878 trough that corresponds to VALUE or the current value if None is
2879 given."""
2880
2881 return self._getints(self.tk.call(self._w, 'coords', value))
2882 def identify(self, x, y):
2883 """Return where the point X,Y lies. Valid return values are "slider",
2884 "though1" and "though2"."""
2885 return self.tk.call(self._w, 'identify', x, y)
Guido van Rossum18468821994-06-20 07:49:28 +00002886
2887class Scrollbar(Widget):
Fredrik Lundh06d28152000-08-09 18:03:12 +00002888 """Scrollbar widget which displays a slider at a certain position."""
2889 def __init__(self, master=None, cnf={}, **kw):
2890 """Construct a scrollbar widget with the parent MASTER.
Guido van Rossum5917ecb2000-06-29 16:30:50 +00002891
Fredrik Lundh06d28152000-08-09 18:03:12 +00002892 Valid resource names: activebackground, activerelief,
2893 background, bd, bg, borderwidth, command, cursor,
2894 elementborderwidth, highlightbackground,
2895 highlightcolor, highlightthickness, jump, orient,
2896 relief, repeatdelay, repeatinterval, takefocus,
2897 troughcolor, width."""
2898 Widget.__init__(self, master, 'scrollbar', cnf, kw)
2899 def activate(self, index):
2900 """Display the element at INDEX with activebackground and activerelief.
2901 INDEX can be "arrow1","slider" or "arrow2"."""
2902 self.tk.call(self._w, 'activate', index)
2903 def delta(self, deltax, deltay):
2904 """Return the fractional change of the scrollbar setting if it
2905 would be moved by DELTAX or DELTAY pixels."""
2906 return getdouble(
2907 self.tk.call(self._w, 'delta', deltax, deltay))
2908 def fraction(self, x, y):
2909 """Return the fractional value which corresponds to a slider
2910 position of X,Y."""
2911 return getdouble(self.tk.call(self._w, 'fraction', x, y))
2912 def identify(self, x, y):
2913 """Return the element under position X,Y as one of
2914 "arrow1","slider","arrow2" or ""."""
2915 return self.tk.call(self._w, 'identify', x, y)
2916 def get(self):
2917 """Return the current fractional values (upper and lower end)
2918 of the slider position."""
2919 return self._getdoubles(self.tk.call(self._w, 'get'))
2920 def set(self, *args):
2921 """Set the fractional values of the slider position (upper and
2922 lower ends as value between 0 and 1)."""
2923 self.tk.call((self._w, 'set') + args)
Raymond Hettingerff41c482003-04-06 09:01:11 +00002924
2925
2926
Guilherme Polo1fff0082009-08-14 15:05:30 +00002927class Text(Widget, XView, YView):
Fredrik Lundh06d28152000-08-09 18:03:12 +00002928 """Text widget which can display text in various forms."""
Fredrik Lundh06d28152000-08-09 18:03:12 +00002929 def __init__(self, master=None, cnf={}, **kw):
2930 """Construct a text widget with the parent MASTER.
Raymond Hettingerff41c482003-04-06 09:01:11 +00002931
Martin v. Löwis2ec36272002-10-13 10:22:08 +00002932 STANDARD OPTIONS
Raymond Hettingerff41c482003-04-06 09:01:11 +00002933
Martin v. Löwis2ec36272002-10-13 10:22:08 +00002934 background, borderwidth, cursor,
2935 exportselection, font, foreground,
2936 highlightbackground, highlightcolor,
2937 highlightthickness, insertbackground,
2938 insertborderwidth, insertofftime,
2939 insertontime, insertwidth, padx, pady,
Raymond Hettingerff41c482003-04-06 09:01:11 +00002940 relief, selectbackground,
Martin v. Löwis2ec36272002-10-13 10:22:08 +00002941 selectborderwidth, selectforeground,
Raymond Hettingerff41c482003-04-06 09:01:11 +00002942 setgrid, takefocus,
Martin v. Löwis2ec36272002-10-13 10:22:08 +00002943 xscrollcommand, yscrollcommand,
Guido van Rossum5917ecb2000-06-29 16:30:50 +00002944
Martin v. Löwis2ec36272002-10-13 10:22:08 +00002945 WIDGET-SPECIFIC OPTIONS
Raymond Hettingerff41c482003-04-06 09:01:11 +00002946
Martin v. Löwis2ec36272002-10-13 10:22:08 +00002947 autoseparators, height, maxundo,
Raymond Hettingerff41c482003-04-06 09:01:11 +00002948 spacing1, spacing2, spacing3,
Martin v. Löwis2ec36272002-10-13 10:22:08 +00002949 state, tabs, undo, width, wrap,
Raymond Hettingerff41c482003-04-06 09:01:11 +00002950
Martin v. Löwis2ec36272002-10-13 10:22:08 +00002951 """
Fredrik Lundh06d28152000-08-09 18:03:12 +00002952 Widget.__init__(self, master, 'text', cnf, kw)
2953 def bbox(self, *args):
2954 """Return a tuple of (x,y,width,height) which gives the bounding
2955 box of the visible part of the character at the index in ARGS."""
2956 return self._getints(
2957 self.tk.call((self._w, 'bbox') + args)) or None
2958 def tk_textSelectTo(self, index):
2959 self.tk.call('tk_textSelectTo', self._w, index)
2960 def tk_textBackspace(self):
2961 self.tk.call('tk_textBackspace', self._w)
2962 def tk_textIndexCloser(self, a, b, c):
2963 self.tk.call('tk_textIndexCloser', self._w, a, b, c)
2964 def tk_textResetAnchor(self, index):
2965 self.tk.call('tk_textResetAnchor', self._w, index)
2966 def compare(self, index1, op, index2):
2967 """Return whether between index INDEX1 and index INDEX2 the
2968 relation OP is satisfied. OP is one of <, <=, ==, >=, >, or !=."""
2969 return self.tk.getboolean(self.tk.call(
2970 self._w, 'compare', index1, op, index2))
Martin v. Löwis5c3c4242012-03-13 13:40:42 -07002971 def count(self, index1, index2, *args): # new in Tk 8.5
2972 """Counts the number of relevant things between the two indices.
2973 If index1 is after index2, the result will be a negative number
2974 (and this holds for each of the possible options).
2975
2976 The actual items which are counted depends on the options given by
2977 args. The result is a list of integers, one for the result of each
2978 counting option given. Valid counting options are "chars",
2979 "displaychars", "displayindices", "displaylines", "indices",
2980 "lines", "xpixels" and "ypixels". There is an additional possible
2981 option "update", which if given then all subsequent options ensure
2982 that any possible out of date information is recalculated."""
2983 args = ['-%s' % arg for arg in args if not arg.startswith('-')]
2984 args += [index1, index2]
2985 res = self.tk.call(self._w, 'count', *args) or None
2986 if res is not None and len(args) <= 3:
2987 return (res, )
2988 else:
2989 return res
Fredrik Lundh06d28152000-08-09 18:03:12 +00002990 def debug(self, boolean=None):
2991 """Turn on the internal consistency checks of the B-Tree inside the text
2992 widget according to BOOLEAN."""
2993 return self.tk.getboolean(self.tk.call(
2994 self._w, 'debug', boolean))
2995 def delete(self, index1, index2=None):
2996 """Delete the characters between INDEX1 and INDEX2 (not included)."""
2997 self.tk.call(self._w, 'delete', index1, index2)
2998 def dlineinfo(self, index):
2999 """Return tuple (x,y,width,height,baseline) giving the bounding box
3000 and baseline position of the visible part of the line containing
3001 the character at INDEX."""
3002 return self._getints(self.tk.call(self._w, 'dlineinfo', index))
Guido van Rossum256705b2002-04-23 13:29:43 +00003003 def dump(self, index1, index2=None, command=None, **kw):
3004 """Return the contents of the widget between index1 and index2.
Raymond Hettingerff41c482003-04-06 09:01:11 +00003005
Guido van Rossum256705b2002-04-23 13:29:43 +00003006 The type of contents returned in filtered based on the keyword
3007 parameters; if 'all', 'image', 'mark', 'tag', 'text', or 'window' are
3008 given and true, then the corresponding items are returned. The result
3009 is a list of triples of the form (key, value, index). If none of the
3010 keywords are true then 'all' is used by default.
Raymond Hettingerff41c482003-04-06 09:01:11 +00003011
Guido van Rossum256705b2002-04-23 13:29:43 +00003012 If the 'command' argument is given, it is called once for each element
3013 of the list of triples, with the values of each triple serving as the
3014 arguments to the function. In this case the list is not returned."""
3015 args = []
3016 func_name = None
3017 result = None
3018 if not command:
3019 # Never call the dump command without the -command flag, since the
3020 # output could involve Tcl quoting and would be a pain to parse
3021 # right. Instead just set the command to build a list of triples
3022 # as if we had done the parsing.
3023 result = []
3024 def append_triple(key, value, index, result=result):
3025 result.append((key, value, index))
3026 command = append_triple
3027 try:
3028 if not isinstance(command, str):
3029 func_name = command = self._register(command)
3030 args += ["-command", command]
3031 for key in kw:
3032 if kw[key]: args.append("-" + key)
3033 args.append(index1)
3034 if index2:
3035 args.append(index2)
3036 self.tk.call(self._w, "dump", *args)
3037 return result
3038 finally:
3039 if func_name:
3040 self.deletecommand(func_name)
Raymond Hettingerff41c482003-04-06 09:01:11 +00003041
Martin v. Löwis2ec36272002-10-13 10:22:08 +00003042 ## new in tk8.4
3043 def edit(self, *args):
3044 """Internal method
Raymond Hettingerff41c482003-04-06 09:01:11 +00003045
3046 This method controls the undo mechanism and
3047 the modified flag. The exact behavior of the
3048 command depends on the option argument that
3049 follows the edit argument. The following forms
Martin v. Löwis2ec36272002-10-13 10:22:08 +00003050 of the command are currently supported:
Raymond Hettingerff41c482003-04-06 09:01:11 +00003051
Martin v. Löwis2ec36272002-10-13 10:22:08 +00003052 edit_modified, edit_redo, edit_reset, edit_separator
3053 and edit_undo
Raymond Hettingerff41c482003-04-06 09:01:11 +00003054
Martin v. Löwis2ec36272002-10-13 10:22:08 +00003055 """
Georg Brandlb533e262008-05-25 18:19:30 +00003056 return self.tk.call(self._w, 'edit', *args)
Martin v. Löwis2ec36272002-10-13 10:22:08 +00003057
3058 def edit_modified(self, arg=None):
3059 """Get or Set the modified flag
Raymond Hettingerff41c482003-04-06 09:01:11 +00003060
Martin v. Löwis2ec36272002-10-13 10:22:08 +00003061 If arg is not specified, returns the modified
Raymond Hettingerff41c482003-04-06 09:01:11 +00003062 flag of the widget. The insert, delete, edit undo and
3063 edit redo commands or the user can set or clear the
3064 modified flag. If boolean is specified, sets the
Martin v. Löwis2ec36272002-10-13 10:22:08 +00003065 modified flag of the widget to arg.
3066 """
3067 return self.edit("modified", arg)
Raymond Hettingerff41c482003-04-06 09:01:11 +00003068
Martin v. Löwis2ec36272002-10-13 10:22:08 +00003069 def edit_redo(self):
3070 """Redo the last undone edit
Raymond Hettingerff41c482003-04-06 09:01:11 +00003071
3072 When the undo option is true, reapplies the last
3073 undone edits provided no other edits were done since
Martin v. Löwis2ec36272002-10-13 10:22:08 +00003074 then. Generates an error when the redo stack is empty.
3075 Does nothing when the undo option is false.
3076 """
3077 return self.edit("redo")
Raymond Hettingerff41c482003-04-06 09:01:11 +00003078
Martin v. Löwis2ec36272002-10-13 10:22:08 +00003079 def edit_reset(self):
3080 """Clears the undo and redo stacks
3081 """
3082 return self.edit("reset")
Raymond Hettingerff41c482003-04-06 09:01:11 +00003083
Martin v. Löwis2ec36272002-10-13 10:22:08 +00003084 def edit_separator(self):
Raymond Hettingerff41c482003-04-06 09:01:11 +00003085 """Inserts a separator (boundary) on the undo stack.
3086
Martin v. Löwis2ec36272002-10-13 10:22:08 +00003087 Does nothing when the undo option is false
3088 """
3089 return self.edit("separator")
Raymond Hettingerff41c482003-04-06 09:01:11 +00003090
Martin v. Löwis2ec36272002-10-13 10:22:08 +00003091 def edit_undo(self):
Raymond Hettingerff41c482003-04-06 09:01:11 +00003092 """Undoes the last edit action
3093
3094 If the undo option is true. An edit action is defined
3095 as all the insert and delete commands that are recorded
3096 on the undo stack in between two separators. Generates
3097 an error when the undo stack is empty. Does nothing
Martin v. Löwis2ec36272002-10-13 10:22:08 +00003098 when the undo option is false
3099 """
3100 return self.edit("undo")
Raymond Hettingerff41c482003-04-06 09:01:11 +00003101
Fredrik Lundh06d28152000-08-09 18:03:12 +00003102 def get(self, index1, index2=None):
3103 """Return the text from INDEX1 to INDEX2 (not included)."""
3104 return self.tk.call(self._w, 'get', index1, index2)
3105 # (Image commands are new in 8.0)
3106 def image_cget(self, index, option):
3107 """Return the value of OPTION of an embedded image at INDEX."""
3108 if option[:1] != "-":
3109 option = "-" + option
3110 if option[-1:] == "_":
3111 option = option[:-1]
3112 return self.tk.call(self._w, "image", "cget", index, option)
Martin v. Löwis6ce13152002-10-10 14:36:13 +00003113 def image_configure(self, index, cnf=None, **kw):
Fredrik Lundh06d28152000-08-09 18:03:12 +00003114 """Configure an embedded image at INDEX."""
Martin v. Löwis6ce13152002-10-10 14:36:13 +00003115 return self._configure(('image', 'configure', index), cnf, kw)
Fredrik Lundh06d28152000-08-09 18:03:12 +00003116 def image_create(self, index, cnf={}, **kw):
3117 """Create an embedded image at INDEX."""
Raymond Hettingerff41c482003-04-06 09:01:11 +00003118 return self.tk.call(
3119 self._w, "image", "create", index,
3120 *self._options(cnf, kw))
Fredrik Lundh06d28152000-08-09 18:03:12 +00003121 def image_names(self):
3122 """Return all names of embedded images in this widget."""
3123 return self.tk.call(self._w, "image", "names")
3124 def index(self, index):
3125 """Return the index in the form line.char for INDEX."""
Christian Heimes57dddfb2008-01-02 18:30:52 +00003126 return str(self.tk.call(self._w, 'index', index))
Fredrik Lundh06d28152000-08-09 18:03:12 +00003127 def insert(self, index, chars, *args):
3128 """Insert CHARS before the characters at INDEX. An additional
3129 tag can be given in ARGS. Additional CHARS and tags can follow in ARGS."""
3130 self.tk.call((self._w, 'insert', index, chars) + args)
3131 def mark_gravity(self, markName, direction=None):
3132 """Change the gravity of a mark MARKNAME to DIRECTION (LEFT or RIGHT).
3133 Return the current value if None is given for DIRECTION."""
3134 return self.tk.call(
3135 (self._w, 'mark', 'gravity', markName, direction))
3136 def mark_names(self):
3137 """Return all mark names."""
3138 return self.tk.splitlist(self.tk.call(
3139 self._w, 'mark', 'names'))
3140 def mark_set(self, markName, index):
3141 """Set mark MARKNAME before the character at INDEX."""
3142 self.tk.call(self._w, 'mark', 'set', markName, index)
3143 def mark_unset(self, *markNames):
3144 """Delete all marks in MARKNAMES."""
3145 self.tk.call((self._w, 'mark', 'unset') + markNames)
3146 def mark_next(self, index):
3147 """Return the name of the next mark after INDEX."""
3148 return self.tk.call(self._w, 'mark', 'next', index) or None
3149 def mark_previous(self, index):
3150 """Return the name of the previous mark before INDEX."""
3151 return self.tk.call(self._w, 'mark', 'previous', index) or None
Martin v. Löwis5c3c4242012-03-13 13:40:42 -07003152 def peer_create(self, newPathName, cnf={}, **kw): # new in Tk 8.5
3153 """Creates a peer text widget with the given newPathName, and any
3154 optional standard configuration options. By default the peer will
Terry Jan Reedy0f847642013-03-11 18:34:00 -04003155 have the same start and end line as the parent widget, but
Martin v. Löwis5c3c4242012-03-13 13:40:42 -07003156 these can be overriden with the standard configuration options."""
3157 self.tk.call(self._w, 'peer', 'create', newPathName,
3158 *self._options(cnf, kw))
3159 def peer_names(self): # new in Tk 8.5
3160 """Returns a list of peers of this widget (this does not include
3161 the widget itself)."""
3162 return self.tk.splitlist(self.tk.call(self._w, 'peer', 'names'))
3163 def replace(self, index1, index2, chars, *args): # new in Tk 8.5
3164 """Replaces the range of characters between index1 and index2 with
3165 the given characters and tags specified by args.
3166
3167 See the method insert for some more information about args, and the
3168 method delete for information about the indices."""
3169 self.tk.call(self._w, 'replace', index1, index2, chars, *args)
Fredrik Lundh06d28152000-08-09 18:03:12 +00003170 def scan_mark(self, x, y):
3171 """Remember the current X, Y coordinates."""
3172 self.tk.call(self._w, 'scan', 'mark', x, y)
3173 def scan_dragto(self, x, y):
3174 """Adjust the view of the text to 10 times the
3175 difference between X and Y and the coordinates given in
3176 scan_mark."""
3177 self.tk.call(self._w, 'scan', 'dragto', x, y)
3178 def search(self, pattern, index, stopindex=None,
3179 forwards=None, backwards=None, exact=None,
Thomas Wouters89f507f2006-12-13 04:49:30 +00003180 regexp=None, nocase=None, count=None, elide=None):
Fredrik Lundh06d28152000-08-09 18:03:12 +00003181 """Search PATTERN beginning from INDEX until STOPINDEX.
Guilherme Poloae098992009-02-09 16:44:24 +00003182 Return the index of the first character of a match or an
3183 empty string."""
Fredrik Lundh06d28152000-08-09 18:03:12 +00003184 args = [self._w, 'search']
3185 if forwards: args.append('-forwards')
3186 if backwards: args.append('-backwards')
3187 if exact: args.append('-exact')
3188 if regexp: args.append('-regexp')
3189 if nocase: args.append('-nocase')
Thomas Wouters89f507f2006-12-13 04:49:30 +00003190 if elide: args.append('-elide')
Fredrik Lundh06d28152000-08-09 18:03:12 +00003191 if count: args.append('-count'); args.append(count)
Guilherme Poloae098992009-02-09 16:44:24 +00003192 if pattern and pattern[0] == '-': args.append('--')
Fredrik Lundh06d28152000-08-09 18:03:12 +00003193 args.append(pattern)
3194 args.append(index)
3195 if stopindex: args.append(stopindex)
Guilherme Polo56f5be52009-03-07 01:54:57 +00003196 return str(self.tk.call(tuple(args)))
Fredrik Lundh06d28152000-08-09 18:03:12 +00003197 def see(self, index):
3198 """Scroll such that the character at INDEX is visible."""
3199 self.tk.call(self._w, 'see', index)
3200 def tag_add(self, tagName, index1, *args):
3201 """Add tag TAGNAME to all characters between INDEX1 and index2 in ARGS.
3202 Additional pairs of indices may follow in ARGS."""
3203 self.tk.call(
3204 (self._w, 'tag', 'add', tagName, index1) + args)
3205 def tag_unbind(self, tagName, sequence, funcid=None):
3206 """Unbind for all characters with TAGNAME for event SEQUENCE the
3207 function identified with FUNCID."""
3208 self.tk.call(self._w, 'tag', 'bind', tagName, sequence, '')
3209 if funcid:
3210 self.deletecommand(funcid)
3211 def tag_bind(self, tagName, sequence, func, add=None):
3212 """Bind to all characters with TAGNAME at event SEQUENCE a call to function FUNC.
Guido van Rossum5917ecb2000-06-29 16:30:50 +00003213
Fredrik Lundh06d28152000-08-09 18:03:12 +00003214 An additional boolean parameter ADD specifies whether FUNC will be
3215 called additionally to the other bound function or whether it will
3216 replace the previous function. See bind for the return value."""
3217 return self._bind((self._w, 'tag', 'bind', tagName),
3218 sequence, func, add)
3219 def tag_cget(self, tagName, option):
3220 """Return the value of OPTION for tag TAGNAME."""
3221 if option[:1] != '-':
3222 option = '-' + option
3223 if option[-1:] == '_':
3224 option = option[:-1]
3225 return self.tk.call(self._w, 'tag', 'cget', tagName, option)
Martin v. Löwis6ce13152002-10-10 14:36:13 +00003226 def tag_configure(self, tagName, cnf=None, **kw):
Fredrik Lundh06d28152000-08-09 18:03:12 +00003227 """Configure a tag TAGNAME."""
Martin v. Löwis6ce13152002-10-10 14:36:13 +00003228 return self._configure(('tag', 'configure', tagName), cnf, kw)
Fredrik Lundh06d28152000-08-09 18:03:12 +00003229 tag_config = tag_configure
3230 def tag_delete(self, *tagNames):
3231 """Delete all tags in TAGNAMES."""
3232 self.tk.call((self._w, 'tag', 'delete') + tagNames)
3233 def tag_lower(self, tagName, belowThis=None):
3234 """Change the priority of tag TAGNAME such that it is lower
3235 than the priority of BELOWTHIS."""
3236 self.tk.call(self._w, 'tag', 'lower', tagName, belowThis)
3237 def tag_names(self, index=None):
3238 """Return a list of all tag names."""
3239 return self.tk.splitlist(
3240 self.tk.call(self._w, 'tag', 'names', index))
3241 def tag_nextrange(self, tagName, index1, index2=None):
3242 """Return a list of start and end index for the first sequence of
3243 characters between INDEX1 and INDEX2 which all have tag TAGNAME.
3244 The text is searched forward from INDEX1."""
3245 return self.tk.splitlist(self.tk.call(
3246 self._w, 'tag', 'nextrange', tagName, index1, index2))
3247 def tag_prevrange(self, tagName, index1, index2=None):
3248 """Return a list of start and end index for the first sequence of
3249 characters between INDEX1 and INDEX2 which all have tag TAGNAME.
3250 The text is searched backwards from INDEX1."""
3251 return self.tk.splitlist(self.tk.call(
3252 self._w, 'tag', 'prevrange', tagName, index1, index2))
3253 def tag_raise(self, tagName, aboveThis=None):
3254 """Change the priority of tag TAGNAME such that it is higher
3255 than the priority of ABOVETHIS."""
3256 self.tk.call(
3257 self._w, 'tag', 'raise', tagName, aboveThis)
3258 def tag_ranges(self, tagName):
3259 """Return a list of ranges of text which have tag TAGNAME."""
3260 return self.tk.splitlist(self.tk.call(
3261 self._w, 'tag', 'ranges', tagName))
3262 def tag_remove(self, tagName, index1, index2=None):
3263 """Remove tag TAGNAME from all characters between INDEX1 and INDEX2."""
3264 self.tk.call(
3265 self._w, 'tag', 'remove', tagName, index1, index2)
3266 def window_cget(self, index, option):
3267 """Return the value of OPTION of an embedded window at INDEX."""
3268 if option[:1] != '-':
3269 option = '-' + option
3270 if option[-1:] == '_':
3271 option = option[:-1]
3272 return self.tk.call(self._w, 'window', 'cget', index, option)
Martin v. Löwis6ce13152002-10-10 14:36:13 +00003273 def window_configure(self, index, cnf=None, **kw):
Fredrik Lundh06d28152000-08-09 18:03:12 +00003274 """Configure an embedded window at INDEX."""
Martin v. Löwis6ce13152002-10-10 14:36:13 +00003275 return self._configure(('window', 'configure', index), cnf, kw)
Fredrik Lundh06d28152000-08-09 18:03:12 +00003276 window_config = window_configure
3277 def window_create(self, index, cnf={}, **kw):
3278 """Create a window at INDEX."""
3279 self.tk.call(
3280 (self._w, 'window', 'create', index)
3281 + self._options(cnf, kw))
3282 def window_names(self):
3283 """Return all names of embedded windows in this widget."""
3284 return self.tk.splitlist(
3285 self.tk.call(self._w, 'window', 'names'))
Fredrik Lundh06d28152000-08-09 18:03:12 +00003286 def yview_pickplace(self, *what):
3287 """Obsolete function, use see."""
3288 self.tk.call((self._w, 'yview', '-pickplace') + what)
Guido van Rossum18468821994-06-20 07:49:28 +00003289
Martin v. Löwis2ec36272002-10-13 10:22:08 +00003290
Guido van Rossum28574b51996-10-21 15:16:51 +00003291class _setit:
Fredrik Lundh06d28152000-08-09 18:03:12 +00003292 """Internal class. It wraps the command in the widget OptionMenu."""
3293 def __init__(self, var, value, callback=None):
3294 self.__value = value
3295 self.__var = var
3296 self.__callback = callback
3297 def __call__(self, *args):
3298 self.__var.set(self.__value)
3299 if self.__callback:
Raymond Hettingerff41c482003-04-06 09:01:11 +00003300 self.__callback(self.__value, *args)
Guido van Rossum28574b51996-10-21 15:16:51 +00003301
3302class OptionMenu(Menubutton):
Fredrik Lundh06d28152000-08-09 18:03:12 +00003303 """OptionMenu which allows the user to select a value from a menu."""
3304 def __init__(self, master, variable, value, *values, **kwargs):
3305 """Construct an optionmenu widget with the parent MASTER, with
3306 the resource textvariable set to VARIABLE, the initially selected
3307 value VALUE, the other menu values VALUES and an additional
3308 keyword argument command."""
3309 kw = {"borderwidth": 2, "textvariable": variable,
3310 "indicatoron": 1, "relief": RAISED, "anchor": "c",
3311 "highlightthickness": 2}
3312 Widget.__init__(self, master, "menubutton", kw)
3313 self.widgetName = 'tk_optionMenu'
3314 menu = self.__menu = Menu(self, name="menu", tearoff=0)
3315 self.menuname = menu._w
3316 # 'command' is the only supported keyword
3317 callback = kwargs.get('command')
Guido van Rossume014a132006-08-19 16:53:45 +00003318 if 'command' in kwargs:
Fredrik Lundh06d28152000-08-09 18:03:12 +00003319 del kwargs['command']
3320 if kwargs:
Collin Winterce36ad82007-08-30 01:19:48 +00003321 raise TclError('unknown option -'+kwargs.keys()[0])
Fredrik Lundh06d28152000-08-09 18:03:12 +00003322 menu.add_command(label=value,
3323 command=_setit(variable, value, callback))
3324 for v in values:
3325 menu.add_command(label=v,
3326 command=_setit(variable, v, callback))
3327 self["menu"] = menu
Guido van Rossum28574b51996-10-21 15:16:51 +00003328
Fredrik Lundh06d28152000-08-09 18:03:12 +00003329 def __getitem__(self, name):
3330 if name == 'menu':
3331 return self.__menu
3332 return Widget.__getitem__(self, name)
Guido van Rossum28574b51996-10-21 15:16:51 +00003333
Fredrik Lundh06d28152000-08-09 18:03:12 +00003334 def destroy(self):
3335 """Destroy this widget and the associated menu."""
3336 Menubutton.destroy(self)
3337 self.__menu = None
Guido van Rossumbf4d8f91995-09-01 20:35:37 +00003338
Guido van Rossum35f67fb1995-08-04 03:50:29 +00003339class Image:
Fredrik Lundh06d28152000-08-09 18:03:12 +00003340 """Base class for images."""
Martin v. Löwis0d8ce612000-09-08 16:28:30 +00003341 _last_id = 0
Fredrik Lundh06d28152000-08-09 18:03:12 +00003342 def __init__(self, imgtype, name=None, cnf={}, master=None, **kw):
3343 self.name = None
3344 if not master:
3345 master = _default_root
3346 if not master:
Collin Winterce36ad82007-08-30 01:19:48 +00003347 raise RuntimeError('Too early to create image')
Fredrik Lundh06d28152000-08-09 18:03:12 +00003348 self.tk = master.tk
3349 if not name:
Martin v. Löwis0d8ce612000-09-08 16:28:30 +00003350 Image._last_id += 1
Walter Dörwald70a6b492004-02-12 17:35:32 +00003351 name = "pyimage%r" % (Image._last_id,) # tk itself would use image<x>
Fredrik Lundh06d28152000-08-09 18:03:12 +00003352 # The following is needed for systems where id(x)
3353 # can return a negative number, such as Linux/m68k:
3354 if name[0] == '-': name = '_' + name[1:]
3355 if kw and cnf: cnf = _cnfmerge((cnf, kw))
3356 elif kw: cnf = kw
3357 options = ()
3358 for k, v in cnf.items():
Florent Xicluna5d1155c2011-10-28 14:45:05 +02003359 if callable(v):
Fredrik Lundh06d28152000-08-09 18:03:12 +00003360 v = self._register(v)
3361 options = options + ('-'+k, v)
3362 self.tk.call(('image', 'create', imgtype, name,) + options)
3363 self.name = name
3364 def __str__(self): return self.name
3365 def __del__(self):
3366 if self.name:
3367 try:
3368 self.tk.call('image', 'delete', self.name)
3369 except TclError:
3370 # May happen if the root was destroyed
3371 pass
3372 def __setitem__(self, key, value):
3373 self.tk.call(self.name, 'configure', '-'+key, value)
3374 def __getitem__(self, key):
3375 return self.tk.call(self.name, 'configure', '-'+key)
3376 def configure(self, **kw):
3377 """Configure the image."""
3378 res = ()
3379 for k, v in _cnfmerge(kw).items():
3380 if v is not None:
3381 if k[-1] == '_': k = k[:-1]
Florent Xicluna5d1155c2011-10-28 14:45:05 +02003382 if callable(v):
Fredrik Lundh06d28152000-08-09 18:03:12 +00003383 v = self._register(v)
3384 res = res + ('-'+k, v)
3385 self.tk.call((self.name, 'config') + res)
3386 config = configure
3387 def height(self):
3388 """Return the height of the image."""
3389 return getint(
3390 self.tk.call('image', 'height', self.name))
3391 def type(self):
3392 """Return the type of the imgage, e.g. "photo" or "bitmap"."""
3393 return self.tk.call('image', 'type', self.name)
3394 def width(self):
3395 """Return the width of the image."""
3396 return getint(
3397 self.tk.call('image', 'width', self.name))
Guido van Rossum35f67fb1995-08-04 03:50:29 +00003398
3399class PhotoImage(Image):
Fredrik Lundh06d28152000-08-09 18:03:12 +00003400 """Widget which can display colored images in GIF, PPM/PGM format."""
3401 def __init__(self, name=None, cnf={}, master=None, **kw):
3402 """Create an image with NAME.
Guido van Rossum5917ecb2000-06-29 16:30:50 +00003403
Fredrik Lundh06d28152000-08-09 18:03:12 +00003404 Valid resource names: data, format, file, gamma, height, palette,
3405 width."""
Raymond Hettingerff41c482003-04-06 09:01:11 +00003406 Image.__init__(self, 'photo', name, cnf, master, **kw)
Fredrik Lundh06d28152000-08-09 18:03:12 +00003407 def blank(self):
3408 """Display a transparent image."""
3409 self.tk.call(self.name, 'blank')
3410 def cget(self, option):
3411 """Return the value of OPTION."""
3412 return self.tk.call(self.name, 'cget', '-' + option)
3413 # XXX config
3414 def __getitem__(self, key):
3415 return self.tk.call(self.name, 'cget', '-' + key)
3416 # XXX copy -from, -to, ...?
3417 def copy(self):
3418 """Return a new PhotoImage with the same image as this widget."""
3419 destImage = PhotoImage()
3420 self.tk.call(destImage, 'copy', self.name)
3421 return destImage
3422 def zoom(self,x,y=''):
3423 """Return a new PhotoImage with the same image as this widget
3424 but zoom it with X and Y."""
3425 destImage = PhotoImage()
3426 if y=='': y=x
3427 self.tk.call(destImage, 'copy', self.name, '-zoom',x,y)
3428 return destImage
3429 def subsample(self,x,y=''):
3430 """Return a new PhotoImage based on the same image as this widget
3431 but use only every Xth or Yth pixel."""
3432 destImage = PhotoImage()
3433 if y=='': y=x
3434 self.tk.call(destImage, 'copy', self.name, '-subsample',x,y)
3435 return destImage
3436 def get(self, x, y):
3437 """Return the color (red, green, blue) of the pixel at X,Y."""
3438 return self.tk.call(self.name, 'get', x, y)
3439 def put(self, data, to=None):
Mark Dickinson934896d2009-02-21 20:59:32 +00003440 """Put row formatted colors to image starting from
Fredrik Lundh06d28152000-08-09 18:03:12 +00003441 position TO, e.g. image.put("{red green} {blue yellow}", to=(4,6))"""
3442 args = (self.name, 'put', data)
3443 if to:
3444 if to[0] == '-to':
3445 to = to[1:]
3446 args = args + ('-to',) + tuple(to)
3447 self.tk.call(args)
3448 # XXX read
3449 def write(self, filename, format=None, from_coords=None):
3450 """Write image to file FILENAME in FORMAT starting from
3451 position FROM_COORDS."""
3452 args = (self.name, 'write', filename)
3453 if format:
3454 args = args + ('-format', format)
3455 if from_coords:
3456 args = args + ('-from',) + tuple(from_coords)
3457 self.tk.call(args)
Guido van Rossum35f67fb1995-08-04 03:50:29 +00003458
3459class BitmapImage(Image):
Fredrik Lundh06d28152000-08-09 18:03:12 +00003460 """Widget which can display a bitmap."""
3461 def __init__(self, name=None, cnf={}, master=None, **kw):
3462 """Create a bitmap with NAME.
Guido van Rossum5917ecb2000-06-29 16:30:50 +00003463
Fredrik Lundh06d28152000-08-09 18:03:12 +00003464 Valid resource names: background, data, file, foreground, maskdata, maskfile."""
Raymond Hettingerff41c482003-04-06 09:01:11 +00003465 Image.__init__(self, 'bitmap', name, cnf, master, **kw)
Guido van Rossum35f67fb1995-08-04 03:50:29 +00003466
3467def image_names(): return _default_root.tk.call('image', 'names')
3468def image_types(): return _default_root.tk.call('image', 'types')
3469
Martin v. Löwis2ec36272002-10-13 10:22:08 +00003470
Guilherme Polo1fff0082009-08-14 15:05:30 +00003471class Spinbox(Widget, XView):
Martin v. Löwis2ec36272002-10-13 10:22:08 +00003472 """spinbox widget."""
3473 def __init__(self, master=None, cnf={}, **kw):
3474 """Construct a spinbox widget with the parent MASTER.
Raymond Hettingerff41c482003-04-06 09:01:11 +00003475
Martin v. Löwis2ec36272002-10-13 10:22:08 +00003476 STANDARD OPTIONS
Raymond Hettingerff41c482003-04-06 09:01:11 +00003477
Martin v. Löwis2ec36272002-10-13 10:22:08 +00003478 activebackground, background, borderwidth,
3479 cursor, exportselection, font, foreground,
3480 highlightbackground, highlightcolor,
3481 highlightthickness, insertbackground,
3482 insertborderwidth, insertofftime,
Raymond Hettingerff41c482003-04-06 09:01:11 +00003483 insertontime, insertwidth, justify, relief,
3484 repeatdelay, repeatinterval,
Martin v. Löwis2ec36272002-10-13 10:22:08 +00003485 selectbackground, selectborderwidth
3486 selectforeground, takefocus, textvariable
3487 xscrollcommand.
Raymond Hettingerff41c482003-04-06 09:01:11 +00003488
Martin v. Löwis2ec36272002-10-13 10:22:08 +00003489 WIDGET-SPECIFIC OPTIONS
Raymond Hettingerff41c482003-04-06 09:01:11 +00003490
3491 buttonbackground, buttoncursor,
3492 buttondownrelief, buttonuprelief,
3493 command, disabledbackground,
3494 disabledforeground, format, from,
3495 invalidcommand, increment,
3496 readonlybackground, state, to,
Martin v. Löwis2ec36272002-10-13 10:22:08 +00003497 validate, validatecommand values,
3498 width, wrap,
3499 """
3500 Widget.__init__(self, master, 'spinbox', cnf, kw)
Raymond Hettingerff41c482003-04-06 09:01:11 +00003501
Martin v. Löwis2ec36272002-10-13 10:22:08 +00003502 def bbox(self, index):
Raymond Hettingerff41c482003-04-06 09:01:11 +00003503 """Return a tuple of X1,Y1,X2,Y2 coordinates for a
3504 rectangle which encloses the character given by index.
3505
3506 The first two elements of the list give the x and y
3507 coordinates of the upper-left corner of the screen
3508 area covered by the character (in pixels relative
3509 to the widget) and the last two elements give the
3510 width and height of the character, in pixels. The
3511 bounding box may refer to a region outside the
Martin v. Löwis2ec36272002-10-13 10:22:08 +00003512 visible area of the window.
3513 """
3514 return self.tk.call(self._w, 'bbox', index)
Raymond Hettingerff41c482003-04-06 09:01:11 +00003515
Martin v. Löwis2ec36272002-10-13 10:22:08 +00003516 def delete(self, first, last=None):
3517 """Delete one or more elements of the spinbox.
Raymond Hettingerff41c482003-04-06 09:01:11 +00003518
3519 First is the index of the first character to delete,
3520 and last is the index of the character just after
3521 the last one to delete. If last isn't specified it
3522 defaults to first+1, i.e. a single character is
Martin v. Löwis2ec36272002-10-13 10:22:08 +00003523 deleted. This command returns an empty string.
3524 """
3525 return self.tk.call(self._w, 'delete', first, last)
Raymond Hettingerff41c482003-04-06 09:01:11 +00003526
Martin v. Löwis2ec36272002-10-13 10:22:08 +00003527 def get(self):
3528 """Returns the spinbox's string"""
3529 return self.tk.call(self._w, 'get')
Raymond Hettingerff41c482003-04-06 09:01:11 +00003530
Martin v. Löwis2ec36272002-10-13 10:22:08 +00003531 def icursor(self, index):
3532 """Alter the position of the insertion cursor.
Raymond Hettingerff41c482003-04-06 09:01:11 +00003533
3534 The insertion cursor will be displayed just before
Martin v. Löwis2ec36272002-10-13 10:22:08 +00003535 the character given by index. Returns an empty string
3536 """
3537 return self.tk.call(self._w, 'icursor', index)
Raymond Hettingerff41c482003-04-06 09:01:11 +00003538
Martin v. Löwis2ec36272002-10-13 10:22:08 +00003539 def identify(self, x, y):
Raymond Hettingerff41c482003-04-06 09:01:11 +00003540 """Returns the name of the widget at position x, y
3541
Martin v. Löwis2ec36272002-10-13 10:22:08 +00003542 Return value is one of: none, buttondown, buttonup, entry
3543 """
3544 return self.tk.call(self._w, 'identify', x, y)
Raymond Hettingerff41c482003-04-06 09:01:11 +00003545
Martin v. Löwis2ec36272002-10-13 10:22:08 +00003546 def index(self, index):
3547 """Returns the numerical index corresponding to index
3548 """
3549 return self.tk.call(self._w, 'index', index)
Raymond Hettingerff41c482003-04-06 09:01:11 +00003550
Martin v. Löwis2ec36272002-10-13 10:22:08 +00003551 def insert(self, index, s):
Raymond Hettingerff41c482003-04-06 09:01:11 +00003552 """Insert string s at index
3553
Martin v. Löwis2ec36272002-10-13 10:22:08 +00003554 Returns an empty string.
3555 """
3556 return self.tk.call(self._w, 'insert', index, s)
Raymond Hettingerff41c482003-04-06 09:01:11 +00003557
Martin v. Löwis2ec36272002-10-13 10:22:08 +00003558 def invoke(self, element):
3559 """Causes the specified element to be invoked
Raymond Hettingerff41c482003-04-06 09:01:11 +00003560
Martin v. Löwis2ec36272002-10-13 10:22:08 +00003561 The element could be buttondown or buttonup
3562 triggering the action associated with it.
3563 """
3564 return self.tk.call(self._w, 'invoke', element)
Raymond Hettingerff41c482003-04-06 09:01:11 +00003565
Martin v. Löwis2ec36272002-10-13 10:22:08 +00003566 def scan(self, *args):
3567 """Internal function."""
3568 return self._getints(
3569 self.tk.call((self._w, 'scan') + args)) or ()
Raymond Hettingerff41c482003-04-06 09:01:11 +00003570
Martin v. Löwis2ec36272002-10-13 10:22:08 +00003571 def scan_mark(self, x):
Raymond Hettingerff41c482003-04-06 09:01:11 +00003572 """Records x and the current view in the spinbox window;
3573
3574 used in conjunction with later scan dragto commands.
3575 Typically this command is associated with a mouse button
Martin v. Löwis2ec36272002-10-13 10:22:08 +00003576 press in the widget. It returns an empty string.
3577 """
3578 return self.scan("mark", x)
Raymond Hettingerff41c482003-04-06 09:01:11 +00003579
Martin v. Löwis2ec36272002-10-13 10:22:08 +00003580 def scan_dragto(self, x):
Raymond Hettingerff41c482003-04-06 09:01:11 +00003581 """Compute the difference between the given x argument
Martin v. Löwis2ec36272002-10-13 10:22:08 +00003582 and the x argument to the last scan mark command
Raymond Hettingerff41c482003-04-06 09:01:11 +00003583
3584 It then adjusts the view left or right by 10 times the
3585 difference in x-coordinates. This command is typically
3586 associated with mouse motion events in the widget, to
Martin v. Löwis2ec36272002-10-13 10:22:08 +00003587 produce the effect of dragging the spinbox at high speed
3588 through the window. The return value is an empty string.
3589 """
3590 return self.scan("dragto", x)
Raymond Hettingerff41c482003-04-06 09:01:11 +00003591
Martin v. Löwis2ec36272002-10-13 10:22:08 +00003592 def selection(self, *args):
3593 """Internal function."""
3594 return self._getints(
3595 self.tk.call((self._w, 'selection') + args)) or ()
Raymond Hettingerff41c482003-04-06 09:01:11 +00003596
Martin v. Löwis2ec36272002-10-13 10:22:08 +00003597 def selection_adjust(self, index):
3598 """Locate the end of the selection nearest to the character
Raymond Hettingerff41c482003-04-06 09:01:11 +00003599 given by index,
3600
3601 Then adjust that end of the selection to be at index
3602 (i.e including but not going beyond index). The other
Martin v. Löwis2ec36272002-10-13 10:22:08 +00003603 end of the selection is made the anchor point for future
Raymond Hettingerff41c482003-04-06 09:01:11 +00003604 select to commands. If the selection isn't currently in
3605 the spinbox, then a new selection is created to include
3606 the characters between index and the most recent selection
Martin v. Löwis2ec36272002-10-13 10:22:08 +00003607 anchor point, inclusive. Returns an empty string.
3608 """
3609 return self.selection("adjust", index)
Raymond Hettingerff41c482003-04-06 09:01:11 +00003610
Martin v. Löwis2ec36272002-10-13 10:22:08 +00003611 def selection_clear(self):
Raymond Hettingerff41c482003-04-06 09:01:11 +00003612 """Clear the selection
3613
3614 If the selection isn't in this widget then the
Martin v. Löwis2ec36272002-10-13 10:22:08 +00003615 command has no effect. Returns an empty string.
3616 """
3617 return self.selection("clear")
Raymond Hettingerff41c482003-04-06 09:01:11 +00003618
Martin v. Löwis2ec36272002-10-13 10:22:08 +00003619 def selection_element(self, element=None):
Raymond Hettingerff41c482003-04-06 09:01:11 +00003620 """Sets or gets the currently selected element.
3621
3622 If a spinbutton element is specified, it will be
Martin v. Löwis2ec36272002-10-13 10:22:08 +00003623 displayed depressed
3624 """
3625 return self.selection("element", element)
3626
3627###########################################################################
3628
3629class LabelFrame(Widget):
3630 """labelframe widget."""
3631 def __init__(self, master=None, cnf={}, **kw):
3632 """Construct a labelframe widget with the parent MASTER.
Raymond Hettingerff41c482003-04-06 09:01:11 +00003633
Martin v. Löwis2ec36272002-10-13 10:22:08 +00003634 STANDARD OPTIONS
Raymond Hettingerff41c482003-04-06 09:01:11 +00003635
3636 borderwidth, cursor, font, foreground,
3637 highlightbackground, highlightcolor,
3638 highlightthickness, padx, pady, relief,
Martin v. Löwis2ec36272002-10-13 10:22:08 +00003639 takefocus, text
Raymond Hettingerff41c482003-04-06 09:01:11 +00003640
Martin v. Löwis2ec36272002-10-13 10:22:08 +00003641 WIDGET-SPECIFIC OPTIONS
Raymond Hettingerff41c482003-04-06 09:01:11 +00003642
3643 background, class, colormap, container,
3644 height, labelanchor, labelwidget,
Martin v. Löwis2ec36272002-10-13 10:22:08 +00003645 visual, width
3646 """
3647 Widget.__init__(self, master, 'labelframe', cnf, kw)
Raymond Hettingerff41c482003-04-06 09:01:11 +00003648
Martin v. Löwis2ec36272002-10-13 10:22:08 +00003649########################################################################
3650
3651class PanedWindow(Widget):
3652 """panedwindow widget."""
3653 def __init__(self, master=None, cnf={}, **kw):
3654 """Construct a panedwindow widget with the parent MASTER.
Raymond Hettingerff41c482003-04-06 09:01:11 +00003655
Martin v. Löwis2ec36272002-10-13 10:22:08 +00003656 STANDARD OPTIONS
Raymond Hettingerff41c482003-04-06 09:01:11 +00003657
Martin v. Löwis2ec36272002-10-13 10:22:08 +00003658 background, borderwidth, cursor, height,
3659 orient, relief, width
Raymond Hettingerff41c482003-04-06 09:01:11 +00003660
Martin v. Löwis2ec36272002-10-13 10:22:08 +00003661 WIDGET-SPECIFIC OPTIONS
Raymond Hettingerff41c482003-04-06 09:01:11 +00003662
3663 handlepad, handlesize, opaqueresize,
3664 sashcursor, sashpad, sashrelief,
Martin v. Löwis2ec36272002-10-13 10:22:08 +00003665 sashwidth, showhandle,
3666 """
3667 Widget.__init__(self, master, 'panedwindow', cnf, kw)
3668
3669 def add(self, child, **kw):
Raymond Hettingerff41c482003-04-06 09:01:11 +00003670 """Add a child widget to the panedwindow in a new pane.
3671
3672 The child argument is the name of the child widget
3673 followed by pairs of arguments that specify how to
Guilherme Polo86425562009-05-31 21:35:23 +00003674 manage the windows. The possible options and values
3675 are the ones accepted by the paneconfigure method.
Martin v. Löwis2ec36272002-10-13 10:22:08 +00003676 """
3677 self.tk.call((self._w, 'add', child) + self._options(kw))
Raymond Hettingerff41c482003-04-06 09:01:11 +00003678
Martin v. Löwis2ec36272002-10-13 10:22:08 +00003679 def remove(self, child):
3680 """Remove the pane containing child from the panedwindow
Raymond Hettingerff41c482003-04-06 09:01:11 +00003681
Martin v. Löwis2ec36272002-10-13 10:22:08 +00003682 All geometry management options for child will be forgotten.
3683 """
3684 self.tk.call(self._w, 'forget', child)
3685 forget=remove
Raymond Hettingerff41c482003-04-06 09:01:11 +00003686
Martin v. Löwis2ec36272002-10-13 10:22:08 +00003687 def identify(self, x, y):
3688 """Identify the panedwindow component at point x, y
Raymond Hettingerff41c482003-04-06 09:01:11 +00003689
3690 If the point is over a sash or a sash handle, the result
Martin v. Löwis2ec36272002-10-13 10:22:08 +00003691 is a two element list containing the index of the sash or
Raymond Hettingerff41c482003-04-06 09:01:11 +00003692 handle, and a word indicating whether it is over a sash
3693 or a handle, such as {0 sash} or {2 handle}. If the point
3694 is over any other part of the panedwindow, the result is
Martin v. Löwis2ec36272002-10-13 10:22:08 +00003695 an empty list.
3696 """
3697 return self.tk.call(self._w, 'identify', x, y)
Raymond Hettingerff41c482003-04-06 09:01:11 +00003698
Martin v. Löwis2ec36272002-10-13 10:22:08 +00003699 def proxy(self, *args):
3700 """Internal function."""
3701 return self._getints(
Raymond Hettingerff41c482003-04-06 09:01:11 +00003702 self.tk.call((self._w, 'proxy') + args)) or ()
3703
Martin v. Löwis2ec36272002-10-13 10:22:08 +00003704 def proxy_coord(self):
3705 """Return the x and y pair of the most recent proxy location
3706 """
3707 return self.proxy("coord")
Raymond Hettingerff41c482003-04-06 09:01:11 +00003708
Martin v. Löwis2ec36272002-10-13 10:22:08 +00003709 def proxy_forget(self):
3710 """Remove the proxy from the display.
3711 """
3712 return self.proxy("forget")
Raymond Hettingerff41c482003-04-06 09:01:11 +00003713
Martin v. Löwis2ec36272002-10-13 10:22:08 +00003714 def proxy_place(self, x, y):
Raymond Hettingerff41c482003-04-06 09:01:11 +00003715 """Place the proxy at the given x and y coordinates.
Martin v. Löwis2ec36272002-10-13 10:22:08 +00003716 """
3717 return self.proxy("place", x, y)
Raymond Hettingerff41c482003-04-06 09:01:11 +00003718
Martin v. Löwis2ec36272002-10-13 10:22:08 +00003719 def sash(self, *args):
3720 """Internal function."""
3721 return self._getints(
3722 self.tk.call((self._w, 'sash') + args)) or ()
Raymond Hettingerff41c482003-04-06 09:01:11 +00003723
Martin v. Löwis2ec36272002-10-13 10:22:08 +00003724 def sash_coord(self, index):
Raymond Hettingerff41c482003-04-06 09:01:11 +00003725 """Return the current x and y pair for the sash given by index.
3726
3727 Index must be an integer between 0 and 1 less than the
3728 number of panes in the panedwindow. The coordinates given are
3729 those of the top left corner of the region containing the sash.
3730 pathName sash dragto index x y This command computes the
3731 difference between the given coordinates and the coordinates
3732 given to the last sash coord command for the given sash. It then
3733 moves that sash the computed difference. The return value is the
Martin v. Löwis2ec36272002-10-13 10:22:08 +00003734 empty string.
3735 """
3736 return self.sash("coord", index)
Raymond Hettingerff41c482003-04-06 09:01:11 +00003737
Martin v. Löwis2ec36272002-10-13 10:22:08 +00003738 def sash_mark(self, index):
Raymond Hettingerff41c482003-04-06 09:01:11 +00003739 """Records x and y for the sash given by index;
3740
Martin v. Löwis2ec36272002-10-13 10:22:08 +00003741 Used in conjunction with later dragto commands to move the sash.
3742 """
3743 return self.sash("mark", index)
Raymond Hettingerff41c482003-04-06 09:01:11 +00003744
Martin v. Löwis2ec36272002-10-13 10:22:08 +00003745 def sash_place(self, index, x, y):
3746 """Place the sash given by index at the given coordinates
3747 """
3748 return self.sash("place", index, x, y)
Raymond Hettingerff41c482003-04-06 09:01:11 +00003749
Martin v. Löwis2ec36272002-10-13 10:22:08 +00003750 def panecget(self, child, option):
Raymond Hettingerff41c482003-04-06 09:01:11 +00003751 """Query a management option for window.
3752
Martin v. Löwis2ec36272002-10-13 10:22:08 +00003753 Option may be any value allowed by the paneconfigure subcommand
3754 """
3755 return self.tk.call(
3756 (self._w, 'panecget') + (child, '-'+option))
Raymond Hettingerff41c482003-04-06 09:01:11 +00003757
Martin v. Löwis2ec36272002-10-13 10:22:08 +00003758 def paneconfigure(self, tagOrId, cnf=None, **kw):
Raymond Hettingerff41c482003-04-06 09:01:11 +00003759 """Query or modify the management options for window.
3760
Martin v. Löwis2ec36272002-10-13 10:22:08 +00003761 If no option is specified, returns a list describing all
Raymond Hettingerff41c482003-04-06 09:01:11 +00003762 of the available options for pathName. If option is
3763 specified with no value, then the command returns a list
3764 describing the one named option (this list will be identical
3765 to the corresponding sublist of the value returned if no
3766 option is specified). If one or more option-value pairs are
3767 specified, then the command modifies the given widget
3768 option(s) to have the given value(s); in this case the
3769 command returns an empty string. The following options
Martin v. Löwis2ec36272002-10-13 10:22:08 +00003770 are supported:
Raymond Hettingerff41c482003-04-06 09:01:11 +00003771
Martin v. Löwis2ec36272002-10-13 10:22:08 +00003772 after window
Raymond Hettingerff41c482003-04-06 09:01:11 +00003773 Insert the window after the window specified. window
Martin v. Löwis2ec36272002-10-13 10:22:08 +00003774 should be the name of a window already managed by pathName.
3775 before window
Raymond Hettingerff41c482003-04-06 09:01:11 +00003776 Insert the window before the window specified. window
Martin v. Löwis2ec36272002-10-13 10:22:08 +00003777 should be the name of a window already managed by pathName.
3778 height size
Raymond Hettingerff41c482003-04-06 09:01:11 +00003779 Specify a height for the window. The height will be the
3780 outer dimension of the window including its border, if
3781 any. If size is an empty string, or if -height is not
3782 specified, then the height requested internally by the
3783 window will be used initially; the height may later be
3784 adjusted by the movement of sashes in the panedwindow.
Martin v. Löwis2ec36272002-10-13 10:22:08 +00003785 Size may be any value accepted by Tk_GetPixels.
3786 minsize n
Raymond Hettingerff41c482003-04-06 09:01:11 +00003787 Specifies that the size of the window cannot be made
3788 less than n. This constraint only affects the size of
3789 the widget in the paned dimension -- the x dimension
3790 for horizontal panedwindows, the y dimension for
3791 vertical panedwindows. May be any value accepted by
Martin v. Löwis2ec36272002-10-13 10:22:08 +00003792 Tk_GetPixels.
3793 padx n
Raymond Hettingerff41c482003-04-06 09:01:11 +00003794 Specifies a non-negative value indicating how much
3795 extra space to leave on each side of the window in
3796 the X-direction. The value may have any of the forms
Martin v. Löwis2ec36272002-10-13 10:22:08 +00003797 accepted by Tk_GetPixels.
3798 pady n
3799 Specifies a non-negative value indicating how much
Raymond Hettingerff41c482003-04-06 09:01:11 +00003800 extra space to leave on each side of the window in
3801 the Y-direction. The value may have any of the forms
Martin v. Löwis2ec36272002-10-13 10:22:08 +00003802 accepted by Tk_GetPixels.
3803 sticky style
Raymond Hettingerff41c482003-04-06 09:01:11 +00003804 If a window's pane is larger than the requested
3805 dimensions of the window, this option may be used
3806 to position (or stretch) the window within its pane.
3807 Style is a string that contains zero or more of the
3808 characters n, s, e or w. The string can optionally
3809 contains spaces or commas, but they are ignored. Each
3810 letter refers to a side (north, south, east, or west)
3811 that the window will "stick" to. If both n and s
3812 (or e and w) are specified, the window will be
3813 stretched to fill the entire height (or width) of
Martin v. Löwis2ec36272002-10-13 10:22:08 +00003814 its cavity.
3815 width size
Raymond Hettingerff41c482003-04-06 09:01:11 +00003816 Specify a width for the window. The width will be
3817 the outer dimension of the window including its
3818 border, if any. If size is an empty string, or
Martin v. Löwis2ec36272002-10-13 10:22:08 +00003819 if -width is not specified, then the width requested
Raymond Hettingerff41c482003-04-06 09:01:11 +00003820 internally by the window will be used initially; the
3821 width may later be adjusted by the movement of sashes
3822 in the panedwindow. Size may be any value accepted by
Martin v. Löwis2ec36272002-10-13 10:22:08 +00003823 Tk_GetPixels.
Raymond Hettingerff41c482003-04-06 09:01:11 +00003824
Martin v. Löwis2ec36272002-10-13 10:22:08 +00003825 """
3826 if cnf is None and not kw:
3827 cnf = {}
3828 for x in self.tk.split(
3829 self.tk.call(self._w,
3830 'paneconfigure', tagOrId)):
3831 cnf[x[0][1:]] = (x[0][1:],) + x[1:]
3832 return cnf
Guido van Rossum13257902007-06-07 23:15:56 +00003833 if isinstance(cnf, str) and not kw:
Martin v. Löwis2ec36272002-10-13 10:22:08 +00003834 x = self.tk.split(self.tk.call(
3835 self._w, 'paneconfigure', tagOrId, '-'+cnf))
3836 return (x[0][1:],) + x[1:]
3837 self.tk.call((self._w, 'paneconfigure', tagOrId) +
3838 self._options(cnf, kw))
3839 paneconfig = paneconfigure
3840
3841 def panes(self):
3842 """Returns an ordered list of the child panes."""
3843 return self.tk.call(self._w, 'panes')
3844
Guido van Rossumaec5dc91994-06-27 07:55:12 +00003845######################################################################
3846# Extensions:
3847
3848class Studbutton(Button):
Fredrik Lundh06d28152000-08-09 18:03:12 +00003849 def __init__(self, master=None, cnf={}, **kw):
3850 Widget.__init__(self, master, 'studbutton', cnf, kw)
3851 self.bind('<Any-Enter>', self.tkButtonEnter)
3852 self.bind('<Any-Leave>', self.tkButtonLeave)
3853 self.bind('<1>', self.tkButtonDown)
3854 self.bind('<ButtonRelease-1>', self.tkButtonUp)
Guido van Rossumaec5dc91994-06-27 07:55:12 +00003855
3856class Tributton(Button):
Fredrik Lundh06d28152000-08-09 18:03:12 +00003857 def __init__(self, master=None, cnf={}, **kw):
3858 Widget.__init__(self, master, 'tributton', cnf, kw)
3859 self.bind('<Any-Enter>', self.tkButtonEnter)
3860 self.bind('<Any-Leave>', self.tkButtonLeave)
3861 self.bind('<1>', self.tkButtonDown)
3862 self.bind('<ButtonRelease-1>', self.tkButtonUp)
3863 self['fg'] = self['bg']
3864 self['activebackground'] = self['bg']
Guido van Rossum37dcab11996-05-16 16:00:19 +00003865
Guido van Rossumc417ef81996-08-21 23:38:59 +00003866######################################################################
3867# Test:
3868
3869def _test():
Fredrik Lundh06d28152000-08-09 18:03:12 +00003870 root = Tk()
3871 text = "This is Tcl/Tk version %s" % TclVersion
3872 if TclVersion >= 8.1:
Walter Dörwald5de48bd2007-06-11 21:38:39 +00003873 text += "\nThis should be a cedilla: \xe7"
Fredrik Lundh06d28152000-08-09 18:03:12 +00003874 label = Label(root, text=text)
3875 label.pack()
3876 test = Button(root, text="Click me!",
3877 command=lambda root=root: root.test.configure(
3878 text="[%s]" % root.test['text']))
3879 test.pack()
3880 root.test = test
3881 quit = Button(root, text="QUIT", command=root.destroy)
3882 quit.pack()
3883 # The following three commands are needed so the window pops
3884 # up on top on Windows...
3885 root.iconify()
3886 root.update()
3887 root.deiconify()
3888 root.mainloop()
Guido van Rossumc417ef81996-08-21 23:38:59 +00003889
3890if __name__ == '__main__':
Fredrik Lundh06d28152000-08-09 18:03:12 +00003891 _test()