blob: f78d24dabceb8e76cd160389d9b2c906798192a6 [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
Guilherme Polo1fff0082009-08-14 15:05:30 +00002184class Canvas(Widget, XView, YView):
Fredrik Lundh06d28152000-08-09 18:03:12 +00002185 """Canvas widget to display graphical elements like lines or text."""
2186 def __init__(self, master=None, cnf={}, **kw):
2187 """Construct a canvas widget with the parent MASTER.
Guido van Rossum5917ecb2000-06-29 16:30:50 +00002188
Fredrik Lundh06d28152000-08-09 18:03:12 +00002189 Valid resource names: background, bd, bg, borderwidth, closeenough,
2190 confine, cursor, height, highlightbackground, highlightcolor,
2191 highlightthickness, insertbackground, insertborderwidth,
2192 insertofftime, insertontime, insertwidth, offset, relief,
2193 scrollregion, selectbackground, selectborderwidth, selectforeground,
2194 state, takefocus, width, xscrollcommand, xscrollincrement,
2195 yscrollcommand, yscrollincrement."""
2196 Widget.__init__(self, master, 'canvas', cnf, kw)
2197 def addtag(self, *args):
2198 """Internal function."""
2199 self.tk.call((self._w, 'addtag') + args)
2200 def addtag_above(self, newtag, tagOrId):
2201 """Add tag NEWTAG to all items above TAGORID."""
2202 self.addtag(newtag, 'above', tagOrId)
2203 def addtag_all(self, newtag):
2204 """Add tag NEWTAG to all items."""
2205 self.addtag(newtag, 'all')
2206 def addtag_below(self, newtag, tagOrId):
2207 """Add tag NEWTAG to all items below TAGORID."""
2208 self.addtag(newtag, 'below', tagOrId)
2209 def addtag_closest(self, newtag, x, y, halo=None, start=None):
2210 """Add tag NEWTAG to item which is closest to pixel at X, Y.
2211 If several match take the top-most.
2212 All items closer than HALO are considered overlapping (all are
2213 closests). If START is specified the next below this tag is taken."""
2214 self.addtag(newtag, 'closest', x, y, halo, start)
2215 def addtag_enclosed(self, newtag, x1, y1, x2, y2):
2216 """Add tag NEWTAG to all items in the rectangle defined
2217 by X1,Y1,X2,Y2."""
2218 self.addtag(newtag, 'enclosed', x1, y1, x2, y2)
2219 def addtag_overlapping(self, newtag, x1, y1, x2, y2):
2220 """Add tag NEWTAG to all items which overlap the rectangle
2221 defined by X1,Y1,X2,Y2."""
2222 self.addtag(newtag, 'overlapping', x1, y1, x2, y2)
2223 def addtag_withtag(self, newtag, tagOrId):
2224 """Add tag NEWTAG to all items with TAGORID."""
2225 self.addtag(newtag, 'withtag', tagOrId)
2226 def bbox(self, *args):
2227 """Return a tuple of X1,Y1,X2,Y2 coordinates for a rectangle
2228 which encloses all items with tags specified as arguments."""
2229 return self._getints(
2230 self.tk.call((self._w, 'bbox') + args)) or None
2231 def tag_unbind(self, tagOrId, sequence, funcid=None):
2232 """Unbind for all items with TAGORID for event SEQUENCE the
2233 function identified with FUNCID."""
2234 self.tk.call(self._w, 'bind', tagOrId, sequence, '')
2235 if funcid:
2236 self.deletecommand(funcid)
2237 def tag_bind(self, tagOrId, sequence=None, func=None, add=None):
2238 """Bind to all items with TAGORID at event SEQUENCE a call to function FUNC.
Guido van Rossum5917ecb2000-06-29 16:30:50 +00002239
Fredrik Lundh06d28152000-08-09 18:03:12 +00002240 An additional boolean parameter ADD specifies whether FUNC will be
2241 called additionally to the other bound function or whether it will
2242 replace the previous function. See bind for the return value."""
2243 return self._bind((self._w, 'bind', tagOrId),
2244 sequence, func, add)
2245 def canvasx(self, screenx, gridspacing=None):
2246 """Return the canvas x coordinate of pixel position SCREENX rounded
2247 to nearest multiple of GRIDSPACING units."""
2248 return getdouble(self.tk.call(
2249 self._w, 'canvasx', screenx, gridspacing))
2250 def canvasy(self, screeny, gridspacing=None):
2251 """Return the canvas y coordinate of pixel position SCREENY rounded
2252 to nearest multiple of GRIDSPACING units."""
2253 return getdouble(self.tk.call(
2254 self._w, 'canvasy', screeny, gridspacing))
2255 def coords(self, *args):
2256 """Return a list of coordinates for the item given in ARGS."""
2257 # XXX Should use _flatten on args
Alexander Belopolsky022f0492010-11-22 19:40:51 +00002258 return [getdouble(x) for x in
Guido van Rossum0bd54331998-05-19 21:18:13 +00002259 self.tk.splitlist(
Alexander Belopolsky022f0492010-11-22 19:40:51 +00002260 self.tk.call((self._w, 'coords') + args))]
Fredrik Lundh06d28152000-08-09 18:03:12 +00002261 def _create(self, itemType, args, kw): # Args: (val, val, ..., cnf={})
2262 """Internal function."""
2263 args = _flatten(args)
2264 cnf = args[-1]
Guido van Rossum13257902007-06-07 23:15:56 +00002265 if isinstance(cnf, (dict, tuple)):
Fredrik Lundh06d28152000-08-09 18:03:12 +00002266 args = args[:-1]
2267 else:
2268 cnf = {}
Raymond Hettingerff41c482003-04-06 09:01:11 +00002269 return getint(self.tk.call(
2270 self._w, 'create', itemType,
2271 *(args + self._options(cnf, kw))))
Fredrik Lundh06d28152000-08-09 18:03:12 +00002272 def create_arc(self, *args, **kw):
2273 """Create arc shaped region with coordinates x1,y1,x2,y2."""
2274 return self._create('arc', args, kw)
2275 def create_bitmap(self, *args, **kw):
2276 """Create bitmap with coordinates x1,y1."""
2277 return self._create('bitmap', args, kw)
2278 def create_image(self, *args, **kw):
2279 """Create image item with coordinates x1,y1."""
2280 return self._create('image', args, kw)
2281 def create_line(self, *args, **kw):
2282 """Create line with coordinates x1,y1,...,xn,yn."""
2283 return self._create('line', args, kw)
2284 def create_oval(self, *args, **kw):
2285 """Create oval with coordinates x1,y1,x2,y2."""
2286 return self._create('oval', args, kw)
2287 def create_polygon(self, *args, **kw):
2288 """Create polygon with coordinates x1,y1,...,xn,yn."""
2289 return self._create('polygon', args, kw)
2290 def create_rectangle(self, *args, **kw):
2291 """Create rectangle with coordinates x1,y1,x2,y2."""
2292 return self._create('rectangle', args, kw)
2293 def create_text(self, *args, **kw):
2294 """Create text with coordinates x1,y1."""
2295 return self._create('text', args, kw)
2296 def create_window(self, *args, **kw):
2297 """Create window with coordinates x1,y1,x2,y2."""
2298 return self._create('window', args, kw)
2299 def dchars(self, *args):
2300 """Delete characters of text items identified by tag or id in ARGS (possibly
2301 several times) from FIRST to LAST character (including)."""
2302 self.tk.call((self._w, 'dchars') + args)
2303 def delete(self, *args):
2304 """Delete items identified by all tag or ids contained in ARGS."""
2305 self.tk.call((self._w, 'delete') + args)
2306 def dtag(self, *args):
2307 """Delete tag or id given as last arguments in ARGS from items
2308 identified by first argument in ARGS."""
2309 self.tk.call((self._w, 'dtag') + args)
2310 def find(self, *args):
2311 """Internal function."""
2312 return self._getints(
2313 self.tk.call((self._w, 'find') + args)) or ()
2314 def find_above(self, tagOrId):
2315 """Return items above TAGORID."""
2316 return self.find('above', tagOrId)
2317 def find_all(self):
2318 """Return all items."""
2319 return self.find('all')
2320 def find_below(self, tagOrId):
2321 """Return all items below TAGORID."""
2322 return self.find('below', tagOrId)
2323 def find_closest(self, x, y, halo=None, start=None):
2324 """Return item which is closest to pixel at X, Y.
2325 If several match take the top-most.
2326 All items closer than HALO are considered overlapping (all are
2327 closests). If START is specified the next below this tag is taken."""
2328 return self.find('closest', x, y, halo, start)
2329 def find_enclosed(self, x1, y1, x2, y2):
2330 """Return all items in rectangle defined
2331 by X1,Y1,X2,Y2."""
2332 return self.find('enclosed', x1, y1, x2, y2)
2333 def find_overlapping(self, x1, y1, x2, y2):
2334 """Return all items which overlap the rectangle
2335 defined by X1,Y1,X2,Y2."""
2336 return self.find('overlapping', x1, y1, x2, y2)
2337 def find_withtag(self, tagOrId):
2338 """Return all items with TAGORID."""
2339 return self.find('withtag', tagOrId)
2340 def focus(self, *args):
2341 """Set focus to the first item specified in ARGS."""
2342 return self.tk.call((self._w, 'focus') + args)
2343 def gettags(self, *args):
2344 """Return tags associated with the first item specified in ARGS."""
2345 return self.tk.splitlist(
2346 self.tk.call((self._w, 'gettags') + args))
2347 def icursor(self, *args):
2348 """Set cursor at position POS in the item identified by TAGORID.
2349 In ARGS TAGORID must be first."""
2350 self.tk.call((self._w, 'icursor') + args)
2351 def index(self, *args):
2352 """Return position of cursor as integer in item specified in ARGS."""
2353 return getint(self.tk.call((self._w, 'index') + args))
2354 def insert(self, *args):
2355 """Insert TEXT in item TAGORID at position POS. ARGS must
2356 be TAGORID POS TEXT."""
2357 self.tk.call((self._w, 'insert') + args)
2358 def itemcget(self, tagOrId, option):
2359 """Return the resource value for an OPTION for item TAGORID."""
2360 return self.tk.call(
2361 (self._w, 'itemcget') + (tagOrId, '-'+option))
2362 def itemconfigure(self, tagOrId, cnf=None, **kw):
2363 """Configure resources of an item TAGORID.
Guido van Rossum5917ecb2000-06-29 16:30:50 +00002364
Fredrik Lundh06d28152000-08-09 18:03:12 +00002365 The values for resources are specified as keyword
2366 arguments. To get an overview about
2367 the allowed keyword arguments call the method without arguments.
2368 """
Martin v. Löwis6ce13152002-10-10 14:36:13 +00002369 return self._configure(('itemconfigure', tagOrId), cnf, kw)
Fredrik Lundh06d28152000-08-09 18:03:12 +00002370 itemconfig = itemconfigure
2371 # lower, tkraise/lift hide Misc.lower, Misc.tkraise/lift,
2372 # so the preferred name for them is tag_lower, tag_raise
2373 # (similar to tag_bind, and similar to the Text widget);
2374 # unfortunately can't delete the old ones yet (maybe in 1.6)
2375 def tag_lower(self, *args):
2376 """Lower an item TAGORID given in ARGS
2377 (optional below another item)."""
2378 self.tk.call((self._w, 'lower') + args)
2379 lower = tag_lower
2380 def move(self, *args):
2381 """Move an item TAGORID given in ARGS."""
2382 self.tk.call((self._w, 'move') + args)
2383 def postscript(self, cnf={}, **kw):
2384 """Print the contents of the canvas to a postscript
2385 file. Valid options: colormap, colormode, file, fontmap,
2386 height, pageanchor, pageheight, pagewidth, pagex, pagey,
2387 rotate, witdh, x, y."""
2388 return self.tk.call((self._w, 'postscript') +
2389 self._options(cnf, kw))
2390 def tag_raise(self, *args):
2391 """Raise an item TAGORID given in ARGS
2392 (optional above another item)."""
2393 self.tk.call((self._w, 'raise') + args)
2394 lift = tkraise = tag_raise
2395 def scale(self, *args):
2396 """Scale item TAGORID with XORIGIN, YORIGIN, XSCALE, YSCALE."""
2397 self.tk.call((self._w, 'scale') + args)
2398 def scan_mark(self, x, y):
2399 """Remember the current X, Y coordinates."""
2400 self.tk.call(self._w, 'scan', 'mark', x, y)
Neal Norwitze931ed52003-01-10 23:24:32 +00002401 def scan_dragto(self, x, y, gain=10):
2402 """Adjust the view of the canvas to GAIN times the
Fredrik Lundh06d28152000-08-09 18:03:12 +00002403 difference between X and Y and the coordinates given in
2404 scan_mark."""
Neal Norwitze931ed52003-01-10 23:24:32 +00002405 self.tk.call(self._w, 'scan', 'dragto', x, y, gain)
Fredrik Lundh06d28152000-08-09 18:03:12 +00002406 def select_adjust(self, tagOrId, index):
2407 """Adjust the end of the selection near the cursor of an item TAGORID to index."""
2408 self.tk.call(self._w, 'select', 'adjust', tagOrId, index)
2409 def select_clear(self):
2410 """Clear the selection if it is in this widget."""
2411 self.tk.call(self._w, 'select', 'clear')
2412 def select_from(self, tagOrId, index):
2413 """Set the fixed end of a selection in item TAGORID to INDEX."""
2414 self.tk.call(self._w, 'select', 'from', tagOrId, index)
2415 def select_item(self):
2416 """Return the item which has the selection."""
Neal Norwitz58b63bf2002-07-23 02:52:58 +00002417 return self.tk.call(self._w, 'select', 'item') or None
Fredrik Lundh06d28152000-08-09 18:03:12 +00002418 def select_to(self, tagOrId, index):
2419 """Set the variable end of a selection in item TAGORID to INDEX."""
2420 self.tk.call(self._w, 'select', 'to', tagOrId, index)
2421 def type(self, tagOrId):
2422 """Return the type of the item TAGORID."""
2423 return self.tk.call(self._w, 'type', tagOrId) or None
Guido van Rossum18468821994-06-20 07:49:28 +00002424
2425class Checkbutton(Widget):
Fredrik Lundh06d28152000-08-09 18:03:12 +00002426 """Checkbutton widget which is either in on- or off-state."""
2427 def __init__(self, master=None, cnf={}, **kw):
2428 """Construct a checkbutton widget with the parent MASTER.
Guido van Rossum5917ecb2000-06-29 16:30:50 +00002429
Fredrik Lundh06d28152000-08-09 18:03:12 +00002430 Valid resource names: activebackground, activeforeground, anchor,
2431 background, bd, bg, bitmap, borderwidth, command, cursor,
2432 disabledforeground, fg, font, foreground, height,
2433 highlightbackground, highlightcolor, highlightthickness, image,
2434 indicatoron, justify, offvalue, onvalue, padx, pady, relief,
2435 selectcolor, selectimage, state, takefocus, text, textvariable,
2436 underline, variable, width, wraplength."""
2437 Widget.__init__(self, master, 'checkbutton', cnf, kw)
2438 def deselect(self):
2439 """Put the button in off-state."""
2440 self.tk.call(self._w, 'deselect')
2441 def flash(self):
2442 """Flash the button."""
2443 self.tk.call(self._w, 'flash')
2444 def invoke(self):
2445 """Toggle the button and invoke a command if given as resource."""
2446 return self.tk.call(self._w, 'invoke')
2447 def select(self):
2448 """Put the button in on-state."""
2449 self.tk.call(self._w, 'select')
2450 def toggle(self):
2451 """Toggle the button."""
2452 self.tk.call(self._w, 'toggle')
Guido van Rossum18468821994-06-20 07:49:28 +00002453
Guilherme Polo1fff0082009-08-14 15:05:30 +00002454class Entry(Widget, XView):
Fredrik Lundh06d28152000-08-09 18:03:12 +00002455 """Entry widget which allows to display simple text."""
2456 def __init__(self, master=None, cnf={}, **kw):
2457 """Construct an entry widget with the parent MASTER.
Guido van Rossum5917ecb2000-06-29 16:30:50 +00002458
Fredrik Lundh06d28152000-08-09 18:03:12 +00002459 Valid resource names: background, bd, bg, borderwidth, cursor,
2460 exportselection, fg, font, foreground, highlightbackground,
2461 highlightcolor, highlightthickness, insertbackground,
2462 insertborderwidth, insertofftime, insertontime, insertwidth,
2463 invalidcommand, invcmd, justify, relief, selectbackground,
2464 selectborderwidth, selectforeground, show, state, takefocus,
2465 textvariable, validate, validatecommand, vcmd, width,
2466 xscrollcommand."""
2467 Widget.__init__(self, master, 'entry', cnf, kw)
2468 def delete(self, first, last=None):
2469 """Delete text from FIRST to LAST (not included)."""
2470 self.tk.call(self._w, 'delete', first, last)
2471 def get(self):
2472 """Return the text."""
2473 return self.tk.call(self._w, 'get')
2474 def icursor(self, index):
2475 """Insert cursor at INDEX."""
2476 self.tk.call(self._w, 'icursor', index)
2477 def index(self, index):
2478 """Return position of cursor."""
2479 return getint(self.tk.call(
2480 self._w, 'index', index))
2481 def insert(self, index, string):
2482 """Insert STRING at INDEX."""
2483 self.tk.call(self._w, 'insert', index, string)
2484 def scan_mark(self, x):
2485 """Remember the current X, Y coordinates."""
2486 self.tk.call(self._w, 'scan', 'mark', x)
2487 def scan_dragto(self, x):
2488 """Adjust the view of the canvas to 10 times the
2489 difference between X and Y and the coordinates given in
2490 scan_mark."""
2491 self.tk.call(self._w, 'scan', 'dragto', x)
2492 def selection_adjust(self, index):
2493 """Adjust the end of the selection near the cursor to INDEX."""
2494 self.tk.call(self._w, 'selection', 'adjust', index)
2495 select_adjust = selection_adjust
2496 def selection_clear(self):
2497 """Clear the selection if it is in this widget."""
2498 self.tk.call(self._w, 'selection', 'clear')
2499 select_clear = selection_clear
2500 def selection_from(self, index):
2501 """Set the fixed end of a selection to INDEX."""
2502 self.tk.call(self._w, 'selection', 'from', index)
2503 select_from = selection_from
2504 def selection_present(self):
Guilherme Polo1fff0082009-08-14 15:05:30 +00002505 """Return True if there are characters selected in the entry, False
2506 otherwise."""
Fredrik Lundh06d28152000-08-09 18:03:12 +00002507 return self.tk.getboolean(
2508 self.tk.call(self._w, 'selection', 'present'))
2509 select_present = selection_present
2510 def selection_range(self, start, end):
2511 """Set the selection from START to END (not included)."""
2512 self.tk.call(self._w, 'selection', 'range', start, end)
2513 select_range = selection_range
2514 def selection_to(self, index):
2515 """Set the variable end of a selection to INDEX."""
2516 self.tk.call(self._w, 'selection', 'to', index)
2517 select_to = selection_to
Guido van Rossum18468821994-06-20 07:49:28 +00002518
2519class Frame(Widget):
Fredrik Lundh06d28152000-08-09 18:03:12 +00002520 """Frame widget which may contain other widgets and can have a 3D border."""
2521 def __init__(self, master=None, cnf={}, **kw):
2522 """Construct a frame widget with the parent MASTER.
Guido van Rossum5917ecb2000-06-29 16:30:50 +00002523
Fredrik Lundh06d28152000-08-09 18:03:12 +00002524 Valid resource names: background, bd, bg, borderwidth, class,
2525 colormap, container, cursor, height, highlightbackground,
2526 highlightcolor, highlightthickness, relief, takefocus, visual, width."""
2527 cnf = _cnfmerge((cnf, kw))
2528 extra = ()
Guido van Rossume014a132006-08-19 16:53:45 +00002529 if 'class_' in cnf:
Fredrik Lundh06d28152000-08-09 18:03:12 +00002530 extra = ('-class', cnf['class_'])
2531 del cnf['class_']
Guido van Rossume014a132006-08-19 16:53:45 +00002532 elif 'class' in cnf:
Fredrik Lundh06d28152000-08-09 18:03:12 +00002533 extra = ('-class', cnf['class'])
2534 del cnf['class']
2535 Widget.__init__(self, master, 'frame', cnf, {}, extra)
Guido van Rossum18468821994-06-20 07:49:28 +00002536
2537class Label(Widget):
Fredrik Lundh06d28152000-08-09 18:03:12 +00002538 """Label widget which can display text and bitmaps."""
2539 def __init__(self, master=None, cnf={}, **kw):
2540 """Construct a label widget with the parent MASTER.
Raymond Hettingerff41c482003-04-06 09:01:11 +00002541
Martin v. Löwis2ec36272002-10-13 10:22:08 +00002542 STANDARD OPTIONS
Raymond Hettingerff41c482003-04-06 09:01:11 +00002543
2544 activebackground, activeforeground, anchor,
2545 background, bitmap, borderwidth, cursor,
Martin v. Löwis2ec36272002-10-13 10:22:08 +00002546 disabledforeground, font, foreground,
Raymond Hettingerff41c482003-04-06 09:01:11 +00002547 highlightbackground, highlightcolor,
2548 highlightthickness, image, justify,
2549 padx, pady, relief, takefocus, text,
Martin v. Löwis2ec36272002-10-13 10:22:08 +00002550 textvariable, underline, wraplength
Raymond Hettingerff41c482003-04-06 09:01:11 +00002551
Martin v. Löwis2ec36272002-10-13 10:22:08 +00002552 WIDGET-SPECIFIC OPTIONS
Raymond Hettingerff41c482003-04-06 09:01:11 +00002553
Martin v. Löwis2ec36272002-10-13 10:22:08 +00002554 height, state, width
Raymond Hettingerff41c482003-04-06 09:01:11 +00002555
Martin v. Löwis2ec36272002-10-13 10:22:08 +00002556 """
Fredrik Lundh06d28152000-08-09 18:03:12 +00002557 Widget.__init__(self, master, 'label', cnf, kw)
Guido van Rossum761c5ab1995-07-14 15:29:10 +00002558
Guilherme Polo1fff0082009-08-14 15:05:30 +00002559class Listbox(Widget, XView, YView):
Fredrik Lundh06d28152000-08-09 18:03:12 +00002560 """Listbox widget which can display a list of strings."""
2561 def __init__(self, master=None, cnf={}, **kw):
2562 """Construct a listbox widget with the parent MASTER.
Guido van Rossum5917ecb2000-06-29 16:30:50 +00002563
Fredrik Lundh06d28152000-08-09 18:03:12 +00002564 Valid resource names: background, bd, bg, borderwidth, cursor,
2565 exportselection, fg, font, foreground, height, highlightbackground,
2566 highlightcolor, highlightthickness, relief, selectbackground,
2567 selectborderwidth, selectforeground, selectmode, setgrid, takefocus,
2568 width, xscrollcommand, yscrollcommand, listvariable."""
2569 Widget.__init__(self, master, 'listbox', cnf, kw)
2570 def activate(self, index):
2571 """Activate item identified by INDEX."""
2572 self.tk.call(self._w, 'activate', index)
2573 def bbox(self, *args):
2574 """Return a tuple of X1,Y1,X2,Y2 coordinates for a rectangle
2575 which encloses the item identified by index in ARGS."""
2576 return self._getints(
2577 self.tk.call((self._w, 'bbox') + args)) or None
2578 def curselection(self):
2579 """Return list of indices of currently selected item."""
2580 # XXX Ought to apply self._getints()...
2581 return self.tk.splitlist(self.tk.call(
2582 self._w, 'curselection'))
2583 def delete(self, first, last=None):
2584 """Delete items from FIRST to LAST (not included)."""
2585 self.tk.call(self._w, 'delete', first, last)
2586 def get(self, first, last=None):
2587 """Get list of items from FIRST to LAST (not included)."""
2588 if last:
2589 return self.tk.splitlist(self.tk.call(
2590 self._w, 'get', first, last))
2591 else:
2592 return self.tk.call(self._w, 'get', first)
2593 def index(self, index):
2594 """Return index of item identified with INDEX."""
2595 i = self.tk.call(self._w, 'index', index)
2596 if i == 'none': return None
2597 return getint(i)
2598 def insert(self, index, *elements):
2599 """Insert ELEMENTS at INDEX."""
2600 self.tk.call((self._w, 'insert', index) + elements)
2601 def nearest(self, y):
2602 """Get index of item which is nearest to y coordinate Y."""
2603 return getint(self.tk.call(
2604 self._w, 'nearest', y))
2605 def scan_mark(self, x, y):
2606 """Remember the current X, Y coordinates."""
2607 self.tk.call(self._w, 'scan', 'mark', x, y)
2608 def scan_dragto(self, x, y):
2609 """Adjust the view of the listbox to 10 times the
2610 difference between X and Y and the coordinates given in
2611 scan_mark."""
2612 self.tk.call(self._w, 'scan', 'dragto', x, y)
2613 def see(self, index):
2614 """Scroll such that INDEX is visible."""
2615 self.tk.call(self._w, 'see', index)
2616 def selection_anchor(self, index):
2617 """Set the fixed end oft the selection to INDEX."""
2618 self.tk.call(self._w, 'selection', 'anchor', index)
2619 select_anchor = selection_anchor
2620 def selection_clear(self, first, last=None):
2621 """Clear the selection from FIRST to LAST (not included)."""
2622 self.tk.call(self._w,
2623 'selection', 'clear', first, last)
2624 select_clear = selection_clear
2625 def selection_includes(self, index):
2626 """Return 1 if INDEX is part of the selection."""
2627 return self.tk.getboolean(self.tk.call(
2628 self._w, 'selection', 'includes', index))
2629 select_includes = selection_includes
2630 def selection_set(self, first, last=None):
2631 """Set the selection from FIRST to LAST (not included) without
2632 changing the currently selected elements."""
2633 self.tk.call(self._w, 'selection', 'set', first, last)
2634 select_set = selection_set
2635 def size(self):
2636 """Return the number of elements in the listbox."""
2637 return getint(self.tk.call(self._w, 'size'))
Guido van Rossum09f1ad82001-09-05 19:29:56 +00002638 def itemcget(self, index, option):
2639 """Return the resource value for an ITEM and an OPTION."""
2640 return self.tk.call(
2641 (self._w, 'itemcget') + (index, '-'+option))
Guido van Rossuma0adb922001-09-01 18:29:55 +00002642 def itemconfigure(self, index, cnf=None, **kw):
Guido van Rossum09f1ad82001-09-05 19:29:56 +00002643 """Configure resources of an ITEM.
Guido van Rossuma0adb922001-09-01 18:29:55 +00002644
2645 The values for resources are specified as keyword arguments.
2646 To get an overview about the allowed keyword arguments
2647 call the method without arguments.
2648 Valid resource names: background, bg, foreground, fg,
2649 selectbackground, selectforeground."""
Martin v. Löwis6ce13152002-10-10 14:36:13 +00002650 return self._configure(('itemconfigure', index), cnf, kw)
Guido van Rossuma0adb922001-09-01 18:29:55 +00002651 itemconfig = itemconfigure
Guido van Rossum18468821994-06-20 07:49:28 +00002652
2653class Menu(Widget):
Fredrik Lundh06d28152000-08-09 18:03:12 +00002654 """Menu widget which allows to display menu bars, pull-down menus and pop-up menus."""
2655 def __init__(self, master=None, cnf={}, **kw):
2656 """Construct menu widget with the parent MASTER.
Guido van Rossum5917ecb2000-06-29 16:30:50 +00002657
Fredrik Lundh06d28152000-08-09 18:03:12 +00002658 Valid resource names: activebackground, activeborderwidth,
2659 activeforeground, background, bd, bg, borderwidth, cursor,
2660 disabledforeground, fg, font, foreground, postcommand, relief,
2661 selectcolor, takefocus, tearoff, tearoffcommand, title, type."""
2662 Widget.__init__(self, master, 'menu', cnf, kw)
2663 def tk_bindForTraversal(self):
2664 pass # obsolete since Tk 4.0
2665 def tk_mbPost(self):
2666 self.tk.call('tk_mbPost', self._w)
2667 def tk_mbUnpost(self):
2668 self.tk.call('tk_mbUnpost')
2669 def tk_traverseToMenu(self, char):
2670 self.tk.call('tk_traverseToMenu', self._w, char)
2671 def tk_traverseWithinMenu(self, char):
2672 self.tk.call('tk_traverseWithinMenu', self._w, char)
2673 def tk_getMenuButtons(self):
2674 return self.tk.call('tk_getMenuButtons', self._w)
2675 def tk_nextMenu(self, count):
2676 self.tk.call('tk_nextMenu', count)
2677 def tk_nextMenuEntry(self, count):
2678 self.tk.call('tk_nextMenuEntry', count)
2679 def tk_invokeMenu(self):
2680 self.tk.call('tk_invokeMenu', self._w)
2681 def tk_firstMenu(self):
2682 self.tk.call('tk_firstMenu', self._w)
2683 def tk_mbButtonDown(self):
2684 self.tk.call('tk_mbButtonDown', self._w)
2685 def tk_popup(self, x, y, entry=""):
2686 """Post the menu at position X,Y with entry ENTRY."""
2687 self.tk.call('tk_popup', self._w, x, y, entry)
2688 def activate(self, index):
2689 """Activate entry at INDEX."""
2690 self.tk.call(self._w, 'activate', index)
2691 def add(self, itemType, cnf={}, **kw):
2692 """Internal function."""
2693 self.tk.call((self._w, 'add', itemType) +
2694 self._options(cnf, kw))
2695 def add_cascade(self, cnf={}, **kw):
2696 """Add hierarchical menu item."""
2697 self.add('cascade', cnf or kw)
2698 def add_checkbutton(self, cnf={}, **kw):
2699 """Add checkbutton menu item."""
2700 self.add('checkbutton', cnf or kw)
2701 def add_command(self, cnf={}, **kw):
2702 """Add command menu item."""
2703 self.add('command', cnf or kw)
2704 def add_radiobutton(self, cnf={}, **kw):
2705 """Addd radio menu item."""
2706 self.add('radiobutton', cnf or kw)
2707 def add_separator(self, cnf={}, **kw):
2708 """Add separator."""
2709 self.add('separator', cnf or kw)
2710 def insert(self, index, itemType, cnf={}, **kw):
2711 """Internal function."""
2712 self.tk.call((self._w, 'insert', index, itemType) +
2713 self._options(cnf, kw))
2714 def insert_cascade(self, index, cnf={}, **kw):
2715 """Add hierarchical menu item at INDEX."""
2716 self.insert(index, 'cascade', cnf or kw)
2717 def insert_checkbutton(self, index, cnf={}, **kw):
2718 """Add checkbutton menu item at INDEX."""
2719 self.insert(index, 'checkbutton', cnf or kw)
2720 def insert_command(self, index, cnf={}, **kw):
2721 """Add command menu item at INDEX."""
2722 self.insert(index, 'command', cnf or kw)
2723 def insert_radiobutton(self, index, cnf={}, **kw):
2724 """Addd radio menu item at INDEX."""
2725 self.insert(index, 'radiobutton', cnf or kw)
2726 def insert_separator(self, index, cnf={}, **kw):
2727 """Add separator at INDEX."""
2728 self.insert(index, 'separator', cnf or kw)
2729 def delete(self, index1, index2=None):
Hirokazu Yamamotoa18424c2008-11-04 06:26:27 +00002730 """Delete menu items between INDEX1 and INDEX2 (included)."""
Robert Schuppenies3d1c7de2008-08-10 11:28:17 +00002731 if index2 is None:
2732 index2 = index1
Robert Schuppenies3d1c7de2008-08-10 11:28:17 +00002733
Hirokazu Yamamotoa18424c2008-11-04 06:26:27 +00002734 num_index1, num_index2 = self.index(index1), self.index(index2)
2735 if (num_index1 is None) or (num_index2 is None):
2736 num_index1, num_index2 = 0, -1
2737
2738 for i in range(num_index1, num_index2 + 1):
2739 if 'command' in self.entryconfig(i):
2740 c = str(self.entrycget(i, 'command'))
2741 if c:
2742 self.deletecommand(c)
2743 self.tk.call(self._w, 'delete', index1, index2)
Fredrik Lundh06d28152000-08-09 18:03:12 +00002744 def entrycget(self, index, option):
2745 """Return the resource value of an menu item for OPTION at INDEX."""
2746 return self.tk.call(self._w, 'entrycget', index, '-' + option)
2747 def entryconfigure(self, index, cnf=None, **kw):
2748 """Configure a menu item at INDEX."""
Martin v. Löwis6ce13152002-10-10 14:36:13 +00002749 return self._configure(('entryconfigure', index), cnf, kw)
Fredrik Lundh06d28152000-08-09 18:03:12 +00002750 entryconfig = entryconfigure
2751 def index(self, index):
2752 """Return the index of a menu item identified by INDEX."""
2753 i = self.tk.call(self._w, 'index', index)
2754 if i == 'none': return None
2755 return getint(i)
2756 def invoke(self, index):
2757 """Invoke a menu item identified by INDEX and execute
2758 the associated command."""
2759 return self.tk.call(self._w, 'invoke', index)
2760 def post(self, x, y):
2761 """Display a menu at position X,Y."""
2762 self.tk.call(self._w, 'post', x, y)
2763 def type(self, index):
2764 """Return the type of the menu item at INDEX."""
2765 return self.tk.call(self._w, 'type', index)
2766 def unpost(self):
2767 """Unmap a menu."""
2768 self.tk.call(self._w, 'unpost')
Martin v. Löwis5c3c4242012-03-13 13:40:42 -07002769 def xposition(self, index): # new in Tk 8.5
2770 """Return the x-position of the leftmost pixel of the menu item
2771 at INDEX."""
2772 return getint(self.tk.call(self._w, 'xposition', index))
Fredrik Lundh06d28152000-08-09 18:03:12 +00002773 def yposition(self, index):
2774 """Return the y-position of the topmost pixel of the menu item at INDEX."""
2775 return getint(self.tk.call(
2776 self._w, 'yposition', index))
Guido van Rossum18468821994-06-20 07:49:28 +00002777
2778class Menubutton(Widget):
Fredrik Lundh06d28152000-08-09 18:03:12 +00002779 """Menubutton widget, obsolete since Tk8.0."""
2780 def __init__(self, master=None, cnf={}, **kw):
2781 Widget.__init__(self, master, 'menubutton', cnf, kw)
Guido van Rossum18468821994-06-20 07:49:28 +00002782
2783class Message(Widget):
Fredrik Lundh06d28152000-08-09 18:03:12 +00002784 """Message widget to display multiline text. Obsolete since Label does it too."""
2785 def __init__(self, master=None, cnf={}, **kw):
2786 Widget.__init__(self, master, 'message', cnf, kw)
Guido van Rossum18468821994-06-20 07:49:28 +00002787
2788class Radiobutton(Widget):
Fredrik Lundh06d28152000-08-09 18:03:12 +00002789 """Radiobutton widget which shows only one of several buttons in on-state."""
2790 def __init__(self, master=None, cnf={}, **kw):
2791 """Construct a radiobutton widget with the parent MASTER.
Guido van Rossum5917ecb2000-06-29 16:30:50 +00002792
Fredrik Lundh06d28152000-08-09 18:03:12 +00002793 Valid resource names: activebackground, activeforeground, anchor,
2794 background, bd, bg, bitmap, borderwidth, command, cursor,
2795 disabledforeground, fg, font, foreground, height,
2796 highlightbackground, highlightcolor, highlightthickness, image,
2797 indicatoron, justify, padx, pady, relief, selectcolor, selectimage,
2798 state, takefocus, text, textvariable, underline, value, variable,
2799 width, wraplength."""
2800 Widget.__init__(self, master, 'radiobutton', cnf, kw)
2801 def deselect(self):
2802 """Put the button in off-state."""
Guido van Rossum5917ecb2000-06-29 16:30:50 +00002803
Fredrik Lundh06d28152000-08-09 18:03:12 +00002804 self.tk.call(self._w, 'deselect')
2805 def flash(self):
2806 """Flash the button."""
2807 self.tk.call(self._w, 'flash')
2808 def invoke(self):
2809 """Toggle the button and invoke a command if given as resource."""
2810 return self.tk.call(self._w, 'invoke')
2811 def select(self):
2812 """Put the button in on-state."""
2813 self.tk.call(self._w, 'select')
Guido van Rossum18468821994-06-20 07:49:28 +00002814
2815class Scale(Widget):
Fredrik Lundh06d28152000-08-09 18:03:12 +00002816 """Scale widget which can display a numerical scale."""
2817 def __init__(self, master=None, cnf={}, **kw):
2818 """Construct a scale widget with the parent MASTER.
Guido van Rossum5917ecb2000-06-29 16:30:50 +00002819
Fredrik Lundh06d28152000-08-09 18:03:12 +00002820 Valid resource names: activebackground, background, bigincrement, bd,
2821 bg, borderwidth, command, cursor, digits, fg, font, foreground, from,
2822 highlightbackground, highlightcolor, highlightthickness, label,
2823 length, orient, relief, repeatdelay, repeatinterval, resolution,
2824 showvalue, sliderlength, sliderrelief, state, takefocus,
2825 tickinterval, to, troughcolor, variable, width."""
2826 Widget.__init__(self, master, 'scale', cnf, kw)
2827 def get(self):
2828 """Get the current value as integer or float."""
2829 value = self.tk.call(self._w, 'get')
2830 try:
2831 return getint(value)
2832 except ValueError:
2833 return getdouble(value)
2834 def set(self, value):
2835 """Set the value to VALUE."""
2836 self.tk.call(self._w, 'set', value)
2837 def coords(self, value=None):
2838 """Return a tuple (X,Y) of the point along the centerline of the
2839 trough that corresponds to VALUE or the current value if None is
2840 given."""
2841
2842 return self._getints(self.tk.call(self._w, 'coords', value))
2843 def identify(self, x, y):
2844 """Return where the point X,Y lies. Valid return values are "slider",
2845 "though1" and "though2"."""
2846 return self.tk.call(self._w, 'identify', x, y)
Guido van Rossum18468821994-06-20 07:49:28 +00002847
2848class Scrollbar(Widget):
Fredrik Lundh06d28152000-08-09 18:03:12 +00002849 """Scrollbar widget which displays a slider at a certain position."""
2850 def __init__(self, master=None, cnf={}, **kw):
2851 """Construct a scrollbar widget with the parent MASTER.
Guido van Rossum5917ecb2000-06-29 16:30:50 +00002852
Fredrik Lundh06d28152000-08-09 18:03:12 +00002853 Valid resource names: activebackground, activerelief,
2854 background, bd, bg, borderwidth, command, cursor,
2855 elementborderwidth, highlightbackground,
2856 highlightcolor, highlightthickness, jump, orient,
2857 relief, repeatdelay, repeatinterval, takefocus,
2858 troughcolor, width."""
2859 Widget.__init__(self, master, 'scrollbar', cnf, kw)
2860 def activate(self, index):
2861 """Display the element at INDEX with activebackground and activerelief.
2862 INDEX can be "arrow1","slider" or "arrow2"."""
2863 self.tk.call(self._w, 'activate', index)
2864 def delta(self, deltax, deltay):
2865 """Return the fractional change of the scrollbar setting if it
2866 would be moved by DELTAX or DELTAY pixels."""
2867 return getdouble(
2868 self.tk.call(self._w, 'delta', deltax, deltay))
2869 def fraction(self, x, y):
2870 """Return the fractional value which corresponds to a slider
2871 position of X,Y."""
2872 return getdouble(self.tk.call(self._w, 'fraction', x, y))
2873 def identify(self, x, y):
2874 """Return the element under position X,Y as one of
2875 "arrow1","slider","arrow2" or ""."""
2876 return self.tk.call(self._w, 'identify', x, y)
2877 def get(self):
2878 """Return the current fractional values (upper and lower end)
2879 of the slider position."""
2880 return self._getdoubles(self.tk.call(self._w, 'get'))
2881 def set(self, *args):
2882 """Set the fractional values of the slider position (upper and
2883 lower ends as value between 0 and 1)."""
2884 self.tk.call((self._w, 'set') + args)
Raymond Hettingerff41c482003-04-06 09:01:11 +00002885
2886
2887
Guilherme Polo1fff0082009-08-14 15:05:30 +00002888class Text(Widget, XView, YView):
Fredrik Lundh06d28152000-08-09 18:03:12 +00002889 """Text widget which can display text in various forms."""
Fredrik Lundh06d28152000-08-09 18:03:12 +00002890 def __init__(self, master=None, cnf={}, **kw):
2891 """Construct a text widget with the parent MASTER.
Raymond Hettingerff41c482003-04-06 09:01:11 +00002892
Martin v. Löwis2ec36272002-10-13 10:22:08 +00002893 STANDARD OPTIONS
Raymond Hettingerff41c482003-04-06 09:01:11 +00002894
Martin v. Löwis2ec36272002-10-13 10:22:08 +00002895 background, borderwidth, cursor,
2896 exportselection, font, foreground,
2897 highlightbackground, highlightcolor,
2898 highlightthickness, insertbackground,
2899 insertborderwidth, insertofftime,
2900 insertontime, insertwidth, padx, pady,
Raymond Hettingerff41c482003-04-06 09:01:11 +00002901 relief, selectbackground,
Martin v. Löwis2ec36272002-10-13 10:22:08 +00002902 selectborderwidth, selectforeground,
Raymond Hettingerff41c482003-04-06 09:01:11 +00002903 setgrid, takefocus,
Martin v. Löwis2ec36272002-10-13 10:22:08 +00002904 xscrollcommand, yscrollcommand,
Guido van Rossum5917ecb2000-06-29 16:30:50 +00002905
Martin v. Löwis2ec36272002-10-13 10:22:08 +00002906 WIDGET-SPECIFIC OPTIONS
Raymond Hettingerff41c482003-04-06 09:01:11 +00002907
Martin v. Löwis2ec36272002-10-13 10:22:08 +00002908 autoseparators, height, maxundo,
Raymond Hettingerff41c482003-04-06 09:01:11 +00002909 spacing1, spacing2, spacing3,
Martin v. Löwis2ec36272002-10-13 10:22:08 +00002910 state, tabs, undo, width, wrap,
Raymond Hettingerff41c482003-04-06 09:01:11 +00002911
Martin v. Löwis2ec36272002-10-13 10:22:08 +00002912 """
Fredrik Lundh06d28152000-08-09 18:03:12 +00002913 Widget.__init__(self, master, 'text', cnf, kw)
2914 def bbox(self, *args):
2915 """Return a tuple of (x,y,width,height) which gives the bounding
2916 box of the visible part of the character at the index in ARGS."""
2917 return self._getints(
2918 self.tk.call((self._w, 'bbox') + args)) or None
2919 def tk_textSelectTo(self, index):
2920 self.tk.call('tk_textSelectTo', self._w, index)
2921 def tk_textBackspace(self):
2922 self.tk.call('tk_textBackspace', self._w)
2923 def tk_textIndexCloser(self, a, b, c):
2924 self.tk.call('tk_textIndexCloser', self._w, a, b, c)
2925 def tk_textResetAnchor(self, index):
2926 self.tk.call('tk_textResetAnchor', self._w, index)
2927 def compare(self, index1, op, index2):
2928 """Return whether between index INDEX1 and index INDEX2 the
2929 relation OP is satisfied. OP is one of <, <=, ==, >=, >, or !=."""
2930 return self.tk.getboolean(self.tk.call(
2931 self._w, 'compare', index1, op, index2))
Martin v. Löwis5c3c4242012-03-13 13:40:42 -07002932 def count(self, index1, index2, *args): # new in Tk 8.5
2933 """Counts the number of relevant things between the two indices.
2934 If index1 is after index2, the result will be a negative number
2935 (and this holds for each of the possible options).
2936
2937 The actual items which are counted depends on the options given by
2938 args. The result is a list of integers, one for the result of each
2939 counting option given. Valid counting options are "chars",
2940 "displaychars", "displayindices", "displaylines", "indices",
2941 "lines", "xpixels" and "ypixels". There is an additional possible
2942 option "update", which if given then all subsequent options ensure
2943 that any possible out of date information is recalculated."""
2944 args = ['-%s' % arg for arg in args if not arg.startswith('-')]
2945 args += [index1, index2]
2946 res = self.tk.call(self._w, 'count', *args) or None
2947 if res is not None and len(args) <= 3:
2948 return (res, )
2949 else:
2950 return res
Fredrik Lundh06d28152000-08-09 18:03:12 +00002951 def debug(self, boolean=None):
2952 """Turn on the internal consistency checks of the B-Tree inside the text
2953 widget according to BOOLEAN."""
2954 return self.tk.getboolean(self.tk.call(
2955 self._w, 'debug', boolean))
2956 def delete(self, index1, index2=None):
2957 """Delete the characters between INDEX1 and INDEX2 (not included)."""
2958 self.tk.call(self._w, 'delete', index1, index2)
2959 def dlineinfo(self, index):
2960 """Return tuple (x,y,width,height,baseline) giving the bounding box
2961 and baseline position of the visible part of the line containing
2962 the character at INDEX."""
2963 return self._getints(self.tk.call(self._w, 'dlineinfo', index))
Guido van Rossum256705b2002-04-23 13:29:43 +00002964 def dump(self, index1, index2=None, command=None, **kw):
2965 """Return the contents of the widget between index1 and index2.
Raymond Hettingerff41c482003-04-06 09:01:11 +00002966
Guido van Rossum256705b2002-04-23 13:29:43 +00002967 The type of contents returned in filtered based on the keyword
2968 parameters; if 'all', 'image', 'mark', 'tag', 'text', or 'window' are
2969 given and true, then the corresponding items are returned. The result
2970 is a list of triples of the form (key, value, index). If none of the
2971 keywords are true then 'all' is used by default.
Raymond Hettingerff41c482003-04-06 09:01:11 +00002972
Guido van Rossum256705b2002-04-23 13:29:43 +00002973 If the 'command' argument is given, it is called once for each element
2974 of the list of triples, with the values of each triple serving as the
2975 arguments to the function. In this case the list is not returned."""
2976 args = []
2977 func_name = None
2978 result = None
2979 if not command:
2980 # Never call the dump command without the -command flag, since the
2981 # output could involve Tcl quoting and would be a pain to parse
2982 # right. Instead just set the command to build a list of triples
2983 # as if we had done the parsing.
2984 result = []
2985 def append_triple(key, value, index, result=result):
2986 result.append((key, value, index))
2987 command = append_triple
2988 try:
2989 if not isinstance(command, str):
2990 func_name = command = self._register(command)
2991 args += ["-command", command]
2992 for key in kw:
2993 if kw[key]: args.append("-" + key)
2994 args.append(index1)
2995 if index2:
2996 args.append(index2)
2997 self.tk.call(self._w, "dump", *args)
2998 return result
2999 finally:
3000 if func_name:
3001 self.deletecommand(func_name)
Raymond Hettingerff41c482003-04-06 09:01:11 +00003002
Martin v. Löwis2ec36272002-10-13 10:22:08 +00003003 ## new in tk8.4
3004 def edit(self, *args):
3005 """Internal method
Raymond Hettingerff41c482003-04-06 09:01:11 +00003006
3007 This method controls the undo mechanism and
3008 the modified flag. The exact behavior of the
3009 command depends on the option argument that
3010 follows the edit argument. The following forms
Martin v. Löwis2ec36272002-10-13 10:22:08 +00003011 of the command are currently supported:
Raymond Hettingerff41c482003-04-06 09:01:11 +00003012
Martin v. Löwis2ec36272002-10-13 10:22:08 +00003013 edit_modified, edit_redo, edit_reset, edit_separator
3014 and edit_undo
Raymond Hettingerff41c482003-04-06 09:01:11 +00003015
Martin v. Löwis2ec36272002-10-13 10:22:08 +00003016 """
Georg Brandlb533e262008-05-25 18:19:30 +00003017 return self.tk.call(self._w, 'edit', *args)
Martin v. Löwis2ec36272002-10-13 10:22:08 +00003018
3019 def edit_modified(self, arg=None):
3020 """Get or Set the modified flag
Raymond Hettingerff41c482003-04-06 09:01:11 +00003021
Martin v. Löwis2ec36272002-10-13 10:22:08 +00003022 If arg is not specified, returns the modified
Raymond Hettingerff41c482003-04-06 09:01:11 +00003023 flag of the widget. The insert, delete, edit undo and
3024 edit redo commands or the user can set or clear the
3025 modified flag. If boolean is specified, sets the
Martin v. Löwis2ec36272002-10-13 10:22:08 +00003026 modified flag of the widget to arg.
3027 """
3028 return self.edit("modified", arg)
Raymond Hettingerff41c482003-04-06 09:01:11 +00003029
Martin v. Löwis2ec36272002-10-13 10:22:08 +00003030 def edit_redo(self):
3031 """Redo the last undone edit
Raymond Hettingerff41c482003-04-06 09:01:11 +00003032
3033 When the undo option is true, reapplies the last
3034 undone edits provided no other edits were done since
Martin v. Löwis2ec36272002-10-13 10:22:08 +00003035 then. Generates an error when the redo stack is empty.
3036 Does nothing when the undo option is false.
3037 """
3038 return self.edit("redo")
Raymond Hettingerff41c482003-04-06 09:01:11 +00003039
Martin v. Löwis2ec36272002-10-13 10:22:08 +00003040 def edit_reset(self):
3041 """Clears the undo and redo stacks
3042 """
3043 return self.edit("reset")
Raymond Hettingerff41c482003-04-06 09:01:11 +00003044
Martin v. Löwis2ec36272002-10-13 10:22:08 +00003045 def edit_separator(self):
Raymond Hettingerff41c482003-04-06 09:01:11 +00003046 """Inserts a separator (boundary) on the undo stack.
3047
Martin v. Löwis2ec36272002-10-13 10:22:08 +00003048 Does nothing when the undo option is false
3049 """
3050 return self.edit("separator")
Raymond Hettingerff41c482003-04-06 09:01:11 +00003051
Martin v. Löwis2ec36272002-10-13 10:22:08 +00003052 def edit_undo(self):
Raymond Hettingerff41c482003-04-06 09:01:11 +00003053 """Undoes the last edit action
3054
3055 If the undo option is true. An edit action is defined
3056 as all the insert and delete commands that are recorded
3057 on the undo stack in between two separators. Generates
3058 an error when the undo stack is empty. Does nothing
Martin v. Löwis2ec36272002-10-13 10:22:08 +00003059 when the undo option is false
3060 """
3061 return self.edit("undo")
Raymond Hettingerff41c482003-04-06 09:01:11 +00003062
Fredrik Lundh06d28152000-08-09 18:03:12 +00003063 def get(self, index1, index2=None):
3064 """Return the text from INDEX1 to INDEX2 (not included)."""
3065 return self.tk.call(self._w, 'get', index1, index2)
3066 # (Image commands are new in 8.0)
3067 def image_cget(self, index, option):
3068 """Return the value of OPTION of an embedded image at INDEX."""
3069 if option[:1] != "-":
3070 option = "-" + option
3071 if option[-1:] == "_":
3072 option = option[:-1]
3073 return self.tk.call(self._w, "image", "cget", index, option)
Martin v. Löwis6ce13152002-10-10 14:36:13 +00003074 def image_configure(self, index, cnf=None, **kw):
Fredrik Lundh06d28152000-08-09 18:03:12 +00003075 """Configure an embedded image at INDEX."""
Martin v. Löwis6ce13152002-10-10 14:36:13 +00003076 return self._configure(('image', 'configure', index), cnf, kw)
Fredrik Lundh06d28152000-08-09 18:03:12 +00003077 def image_create(self, index, cnf={}, **kw):
3078 """Create an embedded image at INDEX."""
Raymond Hettingerff41c482003-04-06 09:01:11 +00003079 return self.tk.call(
3080 self._w, "image", "create", index,
3081 *self._options(cnf, kw))
Fredrik Lundh06d28152000-08-09 18:03:12 +00003082 def image_names(self):
3083 """Return all names of embedded images in this widget."""
3084 return self.tk.call(self._w, "image", "names")
3085 def index(self, index):
3086 """Return the index in the form line.char for INDEX."""
Christian Heimes57dddfb2008-01-02 18:30:52 +00003087 return str(self.tk.call(self._w, 'index', index))
Fredrik Lundh06d28152000-08-09 18:03:12 +00003088 def insert(self, index, chars, *args):
3089 """Insert CHARS before the characters at INDEX. An additional
3090 tag can be given in ARGS. Additional CHARS and tags can follow in ARGS."""
3091 self.tk.call((self._w, 'insert', index, chars) + args)
3092 def mark_gravity(self, markName, direction=None):
3093 """Change the gravity of a mark MARKNAME to DIRECTION (LEFT or RIGHT).
3094 Return the current value if None is given for DIRECTION."""
3095 return self.tk.call(
3096 (self._w, 'mark', 'gravity', markName, direction))
3097 def mark_names(self):
3098 """Return all mark names."""
3099 return self.tk.splitlist(self.tk.call(
3100 self._w, 'mark', 'names'))
3101 def mark_set(self, markName, index):
3102 """Set mark MARKNAME before the character at INDEX."""
3103 self.tk.call(self._w, 'mark', 'set', markName, index)
3104 def mark_unset(self, *markNames):
3105 """Delete all marks in MARKNAMES."""
3106 self.tk.call((self._w, 'mark', 'unset') + markNames)
3107 def mark_next(self, index):
3108 """Return the name of the next mark after INDEX."""
3109 return self.tk.call(self._w, 'mark', 'next', index) or None
3110 def mark_previous(self, index):
3111 """Return the name of the previous mark before INDEX."""
3112 return self.tk.call(self._w, 'mark', 'previous', index) or None
Martin v. Löwis5c3c4242012-03-13 13:40:42 -07003113 def peer_create(self, newPathName, cnf={}, **kw): # new in Tk 8.5
3114 """Creates a peer text widget with the given newPathName, and any
3115 optional standard configuration options. By default the peer will
Terry Jan Reedy0f847642013-03-11 18:34:00 -04003116 have the same start and end line as the parent widget, but
Martin v. Löwis5c3c4242012-03-13 13:40:42 -07003117 these can be overriden with the standard configuration options."""
3118 self.tk.call(self._w, 'peer', 'create', newPathName,
3119 *self._options(cnf, kw))
3120 def peer_names(self): # new in Tk 8.5
3121 """Returns a list of peers of this widget (this does not include
3122 the widget itself)."""
3123 return self.tk.splitlist(self.tk.call(self._w, 'peer', 'names'))
3124 def replace(self, index1, index2, chars, *args): # new in Tk 8.5
3125 """Replaces the range of characters between index1 and index2 with
3126 the given characters and tags specified by args.
3127
3128 See the method insert for some more information about args, and the
3129 method delete for information about the indices."""
3130 self.tk.call(self._w, 'replace', index1, index2, chars, *args)
Fredrik Lundh06d28152000-08-09 18:03:12 +00003131 def scan_mark(self, x, y):
3132 """Remember the current X, Y coordinates."""
3133 self.tk.call(self._w, 'scan', 'mark', x, y)
3134 def scan_dragto(self, x, y):
3135 """Adjust the view of the text to 10 times the
3136 difference between X and Y and the coordinates given in
3137 scan_mark."""
3138 self.tk.call(self._w, 'scan', 'dragto', x, y)
3139 def search(self, pattern, index, stopindex=None,
3140 forwards=None, backwards=None, exact=None,
Thomas Wouters89f507f2006-12-13 04:49:30 +00003141 regexp=None, nocase=None, count=None, elide=None):
Fredrik Lundh06d28152000-08-09 18:03:12 +00003142 """Search PATTERN beginning from INDEX until STOPINDEX.
Guilherme Poloae098992009-02-09 16:44:24 +00003143 Return the index of the first character of a match or an
3144 empty string."""
Fredrik Lundh06d28152000-08-09 18:03:12 +00003145 args = [self._w, 'search']
3146 if forwards: args.append('-forwards')
3147 if backwards: args.append('-backwards')
3148 if exact: args.append('-exact')
3149 if regexp: args.append('-regexp')
3150 if nocase: args.append('-nocase')
Thomas Wouters89f507f2006-12-13 04:49:30 +00003151 if elide: args.append('-elide')
Fredrik Lundh06d28152000-08-09 18:03:12 +00003152 if count: args.append('-count'); args.append(count)
Guilherme Poloae098992009-02-09 16:44:24 +00003153 if pattern and pattern[0] == '-': args.append('--')
Fredrik Lundh06d28152000-08-09 18:03:12 +00003154 args.append(pattern)
3155 args.append(index)
3156 if stopindex: args.append(stopindex)
Guilherme Polo56f5be52009-03-07 01:54:57 +00003157 return str(self.tk.call(tuple(args)))
Fredrik Lundh06d28152000-08-09 18:03:12 +00003158 def see(self, index):
3159 """Scroll such that the character at INDEX is visible."""
3160 self.tk.call(self._w, 'see', index)
3161 def tag_add(self, tagName, index1, *args):
3162 """Add tag TAGNAME to all characters between INDEX1 and index2 in ARGS.
3163 Additional pairs of indices may follow in ARGS."""
3164 self.tk.call(
3165 (self._w, 'tag', 'add', tagName, index1) + args)
3166 def tag_unbind(self, tagName, sequence, funcid=None):
3167 """Unbind for all characters with TAGNAME for event SEQUENCE the
3168 function identified with FUNCID."""
3169 self.tk.call(self._w, 'tag', 'bind', tagName, sequence, '')
3170 if funcid:
3171 self.deletecommand(funcid)
3172 def tag_bind(self, tagName, sequence, func, add=None):
3173 """Bind to all characters with TAGNAME at event SEQUENCE a call to function FUNC.
Guido van Rossum5917ecb2000-06-29 16:30:50 +00003174
Fredrik Lundh06d28152000-08-09 18:03:12 +00003175 An additional boolean parameter ADD specifies whether FUNC will be
3176 called additionally to the other bound function or whether it will
3177 replace the previous function. See bind for the return value."""
3178 return self._bind((self._w, 'tag', 'bind', tagName),
3179 sequence, func, add)
3180 def tag_cget(self, tagName, option):
3181 """Return the value of OPTION for tag TAGNAME."""
3182 if option[:1] != '-':
3183 option = '-' + option
3184 if option[-1:] == '_':
3185 option = option[:-1]
3186 return self.tk.call(self._w, 'tag', 'cget', tagName, option)
Martin v. Löwis6ce13152002-10-10 14:36:13 +00003187 def tag_configure(self, tagName, cnf=None, **kw):
Fredrik Lundh06d28152000-08-09 18:03:12 +00003188 """Configure a tag TAGNAME."""
Martin v. Löwis6ce13152002-10-10 14:36:13 +00003189 return self._configure(('tag', 'configure', tagName), cnf, kw)
Fredrik Lundh06d28152000-08-09 18:03:12 +00003190 tag_config = tag_configure
3191 def tag_delete(self, *tagNames):
3192 """Delete all tags in TAGNAMES."""
3193 self.tk.call((self._w, 'tag', 'delete') + tagNames)
3194 def tag_lower(self, tagName, belowThis=None):
3195 """Change the priority of tag TAGNAME such that it is lower
3196 than the priority of BELOWTHIS."""
3197 self.tk.call(self._w, 'tag', 'lower', tagName, belowThis)
3198 def tag_names(self, index=None):
3199 """Return a list of all tag names."""
3200 return self.tk.splitlist(
3201 self.tk.call(self._w, 'tag', 'names', index))
3202 def tag_nextrange(self, tagName, index1, index2=None):
3203 """Return a list of start and end index for the first sequence of
3204 characters between INDEX1 and INDEX2 which all have tag TAGNAME.
3205 The text is searched forward from INDEX1."""
3206 return self.tk.splitlist(self.tk.call(
3207 self._w, 'tag', 'nextrange', tagName, index1, index2))
3208 def tag_prevrange(self, tagName, index1, index2=None):
3209 """Return a list of start and end index for the first sequence of
3210 characters between INDEX1 and INDEX2 which all have tag TAGNAME.
3211 The text is searched backwards from INDEX1."""
3212 return self.tk.splitlist(self.tk.call(
3213 self._w, 'tag', 'prevrange', tagName, index1, index2))
3214 def tag_raise(self, tagName, aboveThis=None):
3215 """Change the priority of tag TAGNAME such that it is higher
3216 than the priority of ABOVETHIS."""
3217 self.tk.call(
3218 self._w, 'tag', 'raise', tagName, aboveThis)
3219 def tag_ranges(self, tagName):
3220 """Return a list of ranges of text which have tag TAGNAME."""
3221 return self.tk.splitlist(self.tk.call(
3222 self._w, 'tag', 'ranges', tagName))
3223 def tag_remove(self, tagName, index1, index2=None):
3224 """Remove tag TAGNAME from all characters between INDEX1 and INDEX2."""
3225 self.tk.call(
3226 self._w, 'tag', 'remove', tagName, index1, index2)
3227 def window_cget(self, index, option):
3228 """Return the value of OPTION of an embedded window at INDEX."""
3229 if option[:1] != '-':
3230 option = '-' + option
3231 if option[-1:] == '_':
3232 option = option[:-1]
3233 return self.tk.call(self._w, 'window', 'cget', index, option)
Martin v. Löwis6ce13152002-10-10 14:36:13 +00003234 def window_configure(self, index, cnf=None, **kw):
Fredrik Lundh06d28152000-08-09 18:03:12 +00003235 """Configure an embedded window at INDEX."""
Martin v. Löwis6ce13152002-10-10 14:36:13 +00003236 return self._configure(('window', 'configure', index), cnf, kw)
Fredrik Lundh06d28152000-08-09 18:03:12 +00003237 window_config = window_configure
3238 def window_create(self, index, cnf={}, **kw):
3239 """Create a window at INDEX."""
3240 self.tk.call(
3241 (self._w, 'window', 'create', index)
3242 + self._options(cnf, kw))
3243 def window_names(self):
3244 """Return all names of embedded windows in this widget."""
3245 return self.tk.splitlist(
3246 self.tk.call(self._w, 'window', 'names'))
Fredrik Lundh06d28152000-08-09 18:03:12 +00003247 def yview_pickplace(self, *what):
3248 """Obsolete function, use see."""
3249 self.tk.call((self._w, 'yview', '-pickplace') + what)
Guido van Rossum18468821994-06-20 07:49:28 +00003250
Martin v. Löwis2ec36272002-10-13 10:22:08 +00003251
Guido van Rossum28574b51996-10-21 15:16:51 +00003252class _setit:
Fredrik Lundh06d28152000-08-09 18:03:12 +00003253 """Internal class. It wraps the command in the widget OptionMenu."""
3254 def __init__(self, var, value, callback=None):
3255 self.__value = value
3256 self.__var = var
3257 self.__callback = callback
3258 def __call__(self, *args):
3259 self.__var.set(self.__value)
3260 if self.__callback:
Raymond Hettingerff41c482003-04-06 09:01:11 +00003261 self.__callback(self.__value, *args)
Guido van Rossum28574b51996-10-21 15:16:51 +00003262
3263class OptionMenu(Menubutton):
Fredrik Lundh06d28152000-08-09 18:03:12 +00003264 """OptionMenu which allows the user to select a value from a menu."""
3265 def __init__(self, master, variable, value, *values, **kwargs):
3266 """Construct an optionmenu widget with the parent MASTER, with
3267 the resource textvariable set to VARIABLE, the initially selected
3268 value VALUE, the other menu values VALUES and an additional
3269 keyword argument command."""
3270 kw = {"borderwidth": 2, "textvariable": variable,
3271 "indicatoron": 1, "relief": RAISED, "anchor": "c",
3272 "highlightthickness": 2}
3273 Widget.__init__(self, master, "menubutton", kw)
3274 self.widgetName = 'tk_optionMenu'
3275 menu = self.__menu = Menu(self, name="menu", tearoff=0)
3276 self.menuname = menu._w
3277 # 'command' is the only supported keyword
3278 callback = kwargs.get('command')
Guido van Rossume014a132006-08-19 16:53:45 +00003279 if 'command' in kwargs:
Fredrik Lundh06d28152000-08-09 18:03:12 +00003280 del kwargs['command']
3281 if kwargs:
Collin Winterce36ad82007-08-30 01:19:48 +00003282 raise TclError('unknown option -'+kwargs.keys()[0])
Fredrik Lundh06d28152000-08-09 18:03:12 +00003283 menu.add_command(label=value,
3284 command=_setit(variable, value, callback))
3285 for v in values:
3286 menu.add_command(label=v,
3287 command=_setit(variable, v, callback))
3288 self["menu"] = menu
Guido van Rossum28574b51996-10-21 15:16:51 +00003289
Fredrik Lundh06d28152000-08-09 18:03:12 +00003290 def __getitem__(self, name):
3291 if name == 'menu':
3292 return self.__menu
3293 return Widget.__getitem__(self, name)
Guido van Rossum28574b51996-10-21 15:16:51 +00003294
Fredrik Lundh06d28152000-08-09 18:03:12 +00003295 def destroy(self):
3296 """Destroy this widget and the associated menu."""
3297 Menubutton.destroy(self)
3298 self.__menu = None
Guido van Rossumbf4d8f91995-09-01 20:35:37 +00003299
Guido van Rossum35f67fb1995-08-04 03:50:29 +00003300class Image:
Fredrik Lundh06d28152000-08-09 18:03:12 +00003301 """Base class for images."""
Martin v. Löwis0d8ce612000-09-08 16:28:30 +00003302 _last_id = 0
Fredrik Lundh06d28152000-08-09 18:03:12 +00003303 def __init__(self, imgtype, name=None, cnf={}, master=None, **kw):
3304 self.name = None
3305 if not master:
3306 master = _default_root
3307 if not master:
Collin Winterce36ad82007-08-30 01:19:48 +00003308 raise RuntimeError('Too early to create image')
Fredrik Lundh06d28152000-08-09 18:03:12 +00003309 self.tk = master.tk
3310 if not name:
Martin v. Löwis0d8ce612000-09-08 16:28:30 +00003311 Image._last_id += 1
Walter Dörwald70a6b492004-02-12 17:35:32 +00003312 name = "pyimage%r" % (Image._last_id,) # tk itself would use image<x>
Fredrik Lundh06d28152000-08-09 18:03:12 +00003313 # The following is needed for systems where id(x)
3314 # can return a negative number, such as Linux/m68k:
3315 if name[0] == '-': name = '_' + name[1:]
3316 if kw and cnf: cnf = _cnfmerge((cnf, kw))
3317 elif kw: cnf = kw
3318 options = ()
3319 for k, v in cnf.items():
Florent Xicluna5d1155c2011-10-28 14:45:05 +02003320 if callable(v):
Fredrik Lundh06d28152000-08-09 18:03:12 +00003321 v = self._register(v)
3322 options = options + ('-'+k, v)
3323 self.tk.call(('image', 'create', imgtype, name,) + options)
3324 self.name = name
3325 def __str__(self): return self.name
3326 def __del__(self):
3327 if self.name:
3328 try:
3329 self.tk.call('image', 'delete', self.name)
3330 except TclError:
3331 # May happen if the root was destroyed
3332 pass
3333 def __setitem__(self, key, value):
3334 self.tk.call(self.name, 'configure', '-'+key, value)
3335 def __getitem__(self, key):
3336 return self.tk.call(self.name, 'configure', '-'+key)
3337 def configure(self, **kw):
3338 """Configure the image."""
3339 res = ()
3340 for k, v in _cnfmerge(kw).items():
3341 if v is not None:
3342 if k[-1] == '_': k = k[:-1]
Florent Xicluna5d1155c2011-10-28 14:45:05 +02003343 if callable(v):
Fredrik Lundh06d28152000-08-09 18:03:12 +00003344 v = self._register(v)
3345 res = res + ('-'+k, v)
3346 self.tk.call((self.name, 'config') + res)
3347 config = configure
3348 def height(self):
3349 """Return the height of the image."""
3350 return getint(
3351 self.tk.call('image', 'height', self.name))
3352 def type(self):
3353 """Return the type of the imgage, e.g. "photo" or "bitmap"."""
3354 return self.tk.call('image', 'type', self.name)
3355 def width(self):
3356 """Return the width of the image."""
3357 return getint(
3358 self.tk.call('image', 'width', self.name))
Guido van Rossum35f67fb1995-08-04 03:50:29 +00003359
3360class PhotoImage(Image):
Fredrik Lundh06d28152000-08-09 18:03:12 +00003361 """Widget which can display colored images in GIF, PPM/PGM format."""
3362 def __init__(self, name=None, cnf={}, master=None, **kw):
3363 """Create an image with NAME.
Guido van Rossum5917ecb2000-06-29 16:30:50 +00003364
Fredrik Lundh06d28152000-08-09 18:03:12 +00003365 Valid resource names: data, format, file, gamma, height, palette,
3366 width."""
Raymond Hettingerff41c482003-04-06 09:01:11 +00003367 Image.__init__(self, 'photo', name, cnf, master, **kw)
Fredrik Lundh06d28152000-08-09 18:03:12 +00003368 def blank(self):
3369 """Display a transparent image."""
3370 self.tk.call(self.name, 'blank')
3371 def cget(self, option):
3372 """Return the value of OPTION."""
3373 return self.tk.call(self.name, 'cget', '-' + option)
3374 # XXX config
3375 def __getitem__(self, key):
3376 return self.tk.call(self.name, 'cget', '-' + key)
3377 # XXX copy -from, -to, ...?
3378 def copy(self):
3379 """Return a new PhotoImage with the same image as this widget."""
3380 destImage = PhotoImage()
3381 self.tk.call(destImage, 'copy', self.name)
3382 return destImage
3383 def zoom(self,x,y=''):
3384 """Return a new PhotoImage with the same image as this widget
3385 but zoom it with X and Y."""
3386 destImage = PhotoImage()
3387 if y=='': y=x
3388 self.tk.call(destImage, 'copy', self.name, '-zoom',x,y)
3389 return destImage
3390 def subsample(self,x,y=''):
3391 """Return a new PhotoImage based on the same image as this widget
3392 but use only every Xth or Yth pixel."""
3393 destImage = PhotoImage()
3394 if y=='': y=x
3395 self.tk.call(destImage, 'copy', self.name, '-subsample',x,y)
3396 return destImage
3397 def get(self, x, y):
3398 """Return the color (red, green, blue) of the pixel at X,Y."""
3399 return self.tk.call(self.name, 'get', x, y)
3400 def put(self, data, to=None):
Mark Dickinson934896d2009-02-21 20:59:32 +00003401 """Put row formatted colors to image starting from
Fredrik Lundh06d28152000-08-09 18:03:12 +00003402 position TO, e.g. image.put("{red green} {blue yellow}", to=(4,6))"""
3403 args = (self.name, 'put', data)
3404 if to:
3405 if to[0] == '-to':
3406 to = to[1:]
3407 args = args + ('-to',) + tuple(to)
3408 self.tk.call(args)
3409 # XXX read
3410 def write(self, filename, format=None, from_coords=None):
3411 """Write image to file FILENAME in FORMAT starting from
3412 position FROM_COORDS."""
3413 args = (self.name, 'write', filename)
3414 if format:
3415 args = args + ('-format', format)
3416 if from_coords:
3417 args = args + ('-from',) + tuple(from_coords)
3418 self.tk.call(args)
Guido van Rossum35f67fb1995-08-04 03:50:29 +00003419
3420class BitmapImage(Image):
Fredrik Lundh06d28152000-08-09 18:03:12 +00003421 """Widget which can display a bitmap."""
3422 def __init__(self, name=None, cnf={}, master=None, **kw):
3423 """Create a bitmap with NAME.
Guido van Rossum5917ecb2000-06-29 16:30:50 +00003424
Fredrik Lundh06d28152000-08-09 18:03:12 +00003425 Valid resource names: background, data, file, foreground, maskdata, maskfile."""
Raymond Hettingerff41c482003-04-06 09:01:11 +00003426 Image.__init__(self, 'bitmap', name, cnf, master, **kw)
Guido van Rossum35f67fb1995-08-04 03:50:29 +00003427
3428def image_names(): return _default_root.tk.call('image', 'names')
3429def image_types(): return _default_root.tk.call('image', 'types')
3430
Martin v. Löwis2ec36272002-10-13 10:22:08 +00003431
Guilherme Polo1fff0082009-08-14 15:05:30 +00003432class Spinbox(Widget, XView):
Martin v. Löwis2ec36272002-10-13 10:22:08 +00003433 """spinbox widget."""
3434 def __init__(self, master=None, cnf={}, **kw):
3435 """Construct a spinbox widget with the parent MASTER.
Raymond Hettingerff41c482003-04-06 09:01:11 +00003436
Martin v. Löwis2ec36272002-10-13 10:22:08 +00003437 STANDARD OPTIONS
Raymond Hettingerff41c482003-04-06 09:01:11 +00003438
Martin v. Löwis2ec36272002-10-13 10:22:08 +00003439 activebackground, background, borderwidth,
3440 cursor, exportselection, font, foreground,
3441 highlightbackground, highlightcolor,
3442 highlightthickness, insertbackground,
3443 insertborderwidth, insertofftime,
Raymond Hettingerff41c482003-04-06 09:01:11 +00003444 insertontime, insertwidth, justify, relief,
3445 repeatdelay, repeatinterval,
Martin v. Löwis2ec36272002-10-13 10:22:08 +00003446 selectbackground, selectborderwidth
3447 selectforeground, takefocus, textvariable
3448 xscrollcommand.
Raymond Hettingerff41c482003-04-06 09:01:11 +00003449
Martin v. Löwis2ec36272002-10-13 10:22:08 +00003450 WIDGET-SPECIFIC OPTIONS
Raymond Hettingerff41c482003-04-06 09:01:11 +00003451
3452 buttonbackground, buttoncursor,
3453 buttondownrelief, buttonuprelief,
3454 command, disabledbackground,
3455 disabledforeground, format, from,
3456 invalidcommand, increment,
3457 readonlybackground, state, to,
Martin v. Löwis2ec36272002-10-13 10:22:08 +00003458 validate, validatecommand values,
3459 width, wrap,
3460 """
3461 Widget.__init__(self, master, 'spinbox', cnf, kw)
Raymond Hettingerff41c482003-04-06 09:01:11 +00003462
Martin v. Löwis2ec36272002-10-13 10:22:08 +00003463 def bbox(self, index):
Raymond Hettingerff41c482003-04-06 09:01:11 +00003464 """Return a tuple of X1,Y1,X2,Y2 coordinates for a
3465 rectangle which encloses the character given by index.
3466
3467 The first two elements of the list give the x and y
3468 coordinates of the upper-left corner of the screen
3469 area covered by the character (in pixels relative
3470 to the widget) and the last two elements give the
3471 width and height of the character, in pixels. The
3472 bounding box may refer to a region outside the
Martin v. Löwis2ec36272002-10-13 10:22:08 +00003473 visible area of the window.
3474 """
3475 return self.tk.call(self._w, 'bbox', index)
Raymond Hettingerff41c482003-04-06 09:01:11 +00003476
Martin v. Löwis2ec36272002-10-13 10:22:08 +00003477 def delete(self, first, last=None):
3478 """Delete one or more elements of the spinbox.
Raymond Hettingerff41c482003-04-06 09:01:11 +00003479
3480 First is the index of the first character to delete,
3481 and last is the index of the character just after
3482 the last one to delete. If last isn't specified it
3483 defaults to first+1, i.e. a single character is
Martin v. Löwis2ec36272002-10-13 10:22:08 +00003484 deleted. This command returns an empty string.
3485 """
3486 return self.tk.call(self._w, 'delete', first, last)
Raymond Hettingerff41c482003-04-06 09:01:11 +00003487
Martin v. Löwis2ec36272002-10-13 10:22:08 +00003488 def get(self):
3489 """Returns the spinbox's string"""
3490 return self.tk.call(self._w, 'get')
Raymond Hettingerff41c482003-04-06 09:01:11 +00003491
Martin v. Löwis2ec36272002-10-13 10:22:08 +00003492 def icursor(self, index):
3493 """Alter the position of the insertion cursor.
Raymond Hettingerff41c482003-04-06 09:01:11 +00003494
3495 The insertion cursor will be displayed just before
Martin v. Löwis2ec36272002-10-13 10:22:08 +00003496 the character given by index. Returns an empty string
3497 """
3498 return self.tk.call(self._w, 'icursor', index)
Raymond Hettingerff41c482003-04-06 09:01:11 +00003499
Martin v. Löwis2ec36272002-10-13 10:22:08 +00003500 def identify(self, x, y):
Raymond Hettingerff41c482003-04-06 09:01:11 +00003501 """Returns the name of the widget at position x, y
3502
Martin v. Löwis2ec36272002-10-13 10:22:08 +00003503 Return value is one of: none, buttondown, buttonup, entry
3504 """
3505 return self.tk.call(self._w, 'identify', x, y)
Raymond Hettingerff41c482003-04-06 09:01:11 +00003506
Martin v. Löwis2ec36272002-10-13 10:22:08 +00003507 def index(self, index):
3508 """Returns the numerical index corresponding to index
3509 """
3510 return self.tk.call(self._w, 'index', index)
Raymond Hettingerff41c482003-04-06 09:01:11 +00003511
Martin v. Löwis2ec36272002-10-13 10:22:08 +00003512 def insert(self, index, s):
Raymond Hettingerff41c482003-04-06 09:01:11 +00003513 """Insert string s at index
3514
Martin v. Löwis2ec36272002-10-13 10:22:08 +00003515 Returns an empty string.
3516 """
3517 return self.tk.call(self._w, 'insert', index, s)
Raymond Hettingerff41c482003-04-06 09:01:11 +00003518
Martin v. Löwis2ec36272002-10-13 10:22:08 +00003519 def invoke(self, element):
3520 """Causes the specified element to be invoked
Raymond Hettingerff41c482003-04-06 09:01:11 +00003521
Martin v. Löwis2ec36272002-10-13 10:22:08 +00003522 The element could be buttondown or buttonup
3523 triggering the action associated with it.
3524 """
3525 return self.tk.call(self._w, 'invoke', element)
Raymond Hettingerff41c482003-04-06 09:01:11 +00003526
Martin v. Löwis2ec36272002-10-13 10:22:08 +00003527 def scan(self, *args):
3528 """Internal function."""
3529 return self._getints(
3530 self.tk.call((self._w, 'scan') + args)) or ()
Raymond Hettingerff41c482003-04-06 09:01:11 +00003531
Martin v. Löwis2ec36272002-10-13 10:22:08 +00003532 def scan_mark(self, x):
Raymond Hettingerff41c482003-04-06 09:01:11 +00003533 """Records x and the current view in the spinbox window;
3534
3535 used in conjunction with later scan dragto commands.
3536 Typically this command is associated with a mouse button
Martin v. Löwis2ec36272002-10-13 10:22:08 +00003537 press in the widget. It returns an empty string.
3538 """
3539 return self.scan("mark", x)
Raymond Hettingerff41c482003-04-06 09:01:11 +00003540
Martin v. Löwis2ec36272002-10-13 10:22:08 +00003541 def scan_dragto(self, x):
Raymond Hettingerff41c482003-04-06 09:01:11 +00003542 """Compute the difference between the given x argument
Martin v. Löwis2ec36272002-10-13 10:22:08 +00003543 and the x argument to the last scan mark command
Raymond Hettingerff41c482003-04-06 09:01:11 +00003544
3545 It then adjusts the view left or right by 10 times the
3546 difference in x-coordinates. This command is typically
3547 associated with mouse motion events in the widget, to
Martin v. Löwis2ec36272002-10-13 10:22:08 +00003548 produce the effect of dragging the spinbox at high speed
3549 through the window. The return value is an empty string.
3550 """
3551 return self.scan("dragto", x)
Raymond Hettingerff41c482003-04-06 09:01:11 +00003552
Martin v. Löwis2ec36272002-10-13 10:22:08 +00003553 def selection(self, *args):
3554 """Internal function."""
3555 return self._getints(
3556 self.tk.call((self._w, 'selection') + args)) or ()
Raymond Hettingerff41c482003-04-06 09:01:11 +00003557
Martin v. Löwis2ec36272002-10-13 10:22:08 +00003558 def selection_adjust(self, index):
3559 """Locate the end of the selection nearest to the character
Raymond Hettingerff41c482003-04-06 09:01:11 +00003560 given by index,
3561
3562 Then adjust that end of the selection to be at index
3563 (i.e including but not going beyond index). The other
Martin v. Löwis2ec36272002-10-13 10:22:08 +00003564 end of the selection is made the anchor point for future
Raymond Hettingerff41c482003-04-06 09:01:11 +00003565 select to commands. If the selection isn't currently in
3566 the spinbox, then a new selection is created to include
3567 the characters between index and the most recent selection
Martin v. Löwis2ec36272002-10-13 10:22:08 +00003568 anchor point, inclusive. Returns an empty string.
3569 """
3570 return self.selection("adjust", index)
Raymond Hettingerff41c482003-04-06 09:01:11 +00003571
Martin v. Löwis2ec36272002-10-13 10:22:08 +00003572 def selection_clear(self):
Raymond Hettingerff41c482003-04-06 09:01:11 +00003573 """Clear the selection
3574
3575 If the selection isn't in this widget then the
Martin v. Löwis2ec36272002-10-13 10:22:08 +00003576 command has no effect. Returns an empty string.
3577 """
3578 return self.selection("clear")
Raymond Hettingerff41c482003-04-06 09:01:11 +00003579
Martin v. Löwis2ec36272002-10-13 10:22:08 +00003580 def selection_element(self, element=None):
Raymond Hettingerff41c482003-04-06 09:01:11 +00003581 """Sets or gets the currently selected element.
3582
3583 If a spinbutton element is specified, it will be
Martin v. Löwis2ec36272002-10-13 10:22:08 +00003584 displayed depressed
3585 """
3586 return self.selection("element", element)
3587
3588###########################################################################
3589
3590class LabelFrame(Widget):
3591 """labelframe widget."""
3592 def __init__(self, master=None, cnf={}, **kw):
3593 """Construct a labelframe widget with the parent MASTER.
Raymond Hettingerff41c482003-04-06 09:01:11 +00003594
Martin v. Löwis2ec36272002-10-13 10:22:08 +00003595 STANDARD OPTIONS
Raymond Hettingerff41c482003-04-06 09:01:11 +00003596
3597 borderwidth, cursor, font, foreground,
3598 highlightbackground, highlightcolor,
3599 highlightthickness, padx, pady, relief,
Martin v. Löwis2ec36272002-10-13 10:22:08 +00003600 takefocus, text
Raymond Hettingerff41c482003-04-06 09:01:11 +00003601
Martin v. Löwis2ec36272002-10-13 10:22:08 +00003602 WIDGET-SPECIFIC OPTIONS
Raymond Hettingerff41c482003-04-06 09:01:11 +00003603
3604 background, class, colormap, container,
3605 height, labelanchor, labelwidget,
Martin v. Löwis2ec36272002-10-13 10:22:08 +00003606 visual, width
3607 """
3608 Widget.__init__(self, master, 'labelframe', cnf, kw)
Raymond Hettingerff41c482003-04-06 09:01:11 +00003609
Martin v. Löwis2ec36272002-10-13 10:22:08 +00003610########################################################################
3611
3612class PanedWindow(Widget):
3613 """panedwindow widget."""
3614 def __init__(self, master=None, cnf={}, **kw):
3615 """Construct a panedwindow widget with the parent MASTER.
Raymond Hettingerff41c482003-04-06 09:01:11 +00003616
Martin v. Löwis2ec36272002-10-13 10:22:08 +00003617 STANDARD OPTIONS
Raymond Hettingerff41c482003-04-06 09:01:11 +00003618
Martin v. Löwis2ec36272002-10-13 10:22:08 +00003619 background, borderwidth, cursor, height,
3620 orient, relief, width
Raymond Hettingerff41c482003-04-06 09:01:11 +00003621
Martin v. Löwis2ec36272002-10-13 10:22:08 +00003622 WIDGET-SPECIFIC OPTIONS
Raymond Hettingerff41c482003-04-06 09:01:11 +00003623
3624 handlepad, handlesize, opaqueresize,
3625 sashcursor, sashpad, sashrelief,
Martin v. Löwis2ec36272002-10-13 10:22:08 +00003626 sashwidth, showhandle,
3627 """
3628 Widget.__init__(self, master, 'panedwindow', cnf, kw)
3629
3630 def add(self, child, **kw):
Raymond Hettingerff41c482003-04-06 09:01:11 +00003631 """Add a child widget to the panedwindow in a new pane.
3632
3633 The child argument is the name of the child widget
3634 followed by pairs of arguments that specify how to
Guilherme Polo86425562009-05-31 21:35:23 +00003635 manage the windows. The possible options and values
3636 are the ones accepted by the paneconfigure method.
Martin v. Löwis2ec36272002-10-13 10:22:08 +00003637 """
3638 self.tk.call((self._w, 'add', child) + self._options(kw))
Raymond Hettingerff41c482003-04-06 09:01:11 +00003639
Martin v. Löwis2ec36272002-10-13 10:22:08 +00003640 def remove(self, child):
3641 """Remove the pane containing child from the panedwindow
Raymond Hettingerff41c482003-04-06 09:01:11 +00003642
Martin v. Löwis2ec36272002-10-13 10:22:08 +00003643 All geometry management options for child will be forgotten.
3644 """
3645 self.tk.call(self._w, 'forget', child)
3646 forget=remove
Raymond Hettingerff41c482003-04-06 09:01:11 +00003647
Martin v. Löwis2ec36272002-10-13 10:22:08 +00003648 def identify(self, x, y):
3649 """Identify the panedwindow component at point x, y
Raymond Hettingerff41c482003-04-06 09:01:11 +00003650
3651 If the point is over a sash or a sash handle, the result
Martin v. Löwis2ec36272002-10-13 10:22:08 +00003652 is a two element list containing the index of the sash or
Raymond Hettingerff41c482003-04-06 09:01:11 +00003653 handle, and a word indicating whether it is over a sash
3654 or a handle, such as {0 sash} or {2 handle}. If the point
3655 is over any other part of the panedwindow, the result is
Martin v. Löwis2ec36272002-10-13 10:22:08 +00003656 an empty list.
3657 """
3658 return self.tk.call(self._w, 'identify', x, y)
Raymond Hettingerff41c482003-04-06 09:01:11 +00003659
Martin v. Löwis2ec36272002-10-13 10:22:08 +00003660 def proxy(self, *args):
3661 """Internal function."""
3662 return self._getints(
Raymond Hettingerff41c482003-04-06 09:01:11 +00003663 self.tk.call((self._w, 'proxy') + args)) or ()
3664
Martin v. Löwis2ec36272002-10-13 10:22:08 +00003665 def proxy_coord(self):
3666 """Return the x and y pair of the most recent proxy location
3667 """
3668 return self.proxy("coord")
Raymond Hettingerff41c482003-04-06 09:01:11 +00003669
Martin v. Löwis2ec36272002-10-13 10:22:08 +00003670 def proxy_forget(self):
3671 """Remove the proxy from the display.
3672 """
3673 return self.proxy("forget")
Raymond Hettingerff41c482003-04-06 09:01:11 +00003674
Martin v. Löwis2ec36272002-10-13 10:22:08 +00003675 def proxy_place(self, x, y):
Raymond Hettingerff41c482003-04-06 09:01:11 +00003676 """Place the proxy at the given x and y coordinates.
Martin v. Löwis2ec36272002-10-13 10:22:08 +00003677 """
3678 return self.proxy("place", x, y)
Raymond Hettingerff41c482003-04-06 09:01:11 +00003679
Martin v. Löwis2ec36272002-10-13 10:22:08 +00003680 def sash(self, *args):
3681 """Internal function."""
3682 return self._getints(
3683 self.tk.call((self._w, 'sash') + args)) or ()
Raymond Hettingerff41c482003-04-06 09:01:11 +00003684
Martin v. Löwis2ec36272002-10-13 10:22:08 +00003685 def sash_coord(self, index):
Raymond Hettingerff41c482003-04-06 09:01:11 +00003686 """Return the current x and y pair for the sash given by index.
3687
3688 Index must be an integer between 0 and 1 less than the
3689 number of panes in the panedwindow. The coordinates given are
3690 those of the top left corner of the region containing the sash.
3691 pathName sash dragto index x y This command computes the
3692 difference between the given coordinates and the coordinates
3693 given to the last sash coord command for the given sash. It then
3694 moves that sash the computed difference. The return value is the
Martin v. Löwis2ec36272002-10-13 10:22:08 +00003695 empty string.
3696 """
3697 return self.sash("coord", index)
Raymond Hettingerff41c482003-04-06 09:01:11 +00003698
Martin v. Löwis2ec36272002-10-13 10:22:08 +00003699 def sash_mark(self, index):
Raymond Hettingerff41c482003-04-06 09:01:11 +00003700 """Records x and y for the sash given by index;
3701
Martin v. Löwis2ec36272002-10-13 10:22:08 +00003702 Used in conjunction with later dragto commands to move the sash.
3703 """
3704 return self.sash("mark", index)
Raymond Hettingerff41c482003-04-06 09:01:11 +00003705
Martin v. Löwis2ec36272002-10-13 10:22:08 +00003706 def sash_place(self, index, x, y):
3707 """Place the sash given by index at the given coordinates
3708 """
3709 return self.sash("place", index, x, y)
Raymond Hettingerff41c482003-04-06 09:01:11 +00003710
Martin v. Löwis2ec36272002-10-13 10:22:08 +00003711 def panecget(self, child, option):
Raymond Hettingerff41c482003-04-06 09:01:11 +00003712 """Query a management option for window.
3713
Martin v. Löwis2ec36272002-10-13 10:22:08 +00003714 Option may be any value allowed by the paneconfigure subcommand
3715 """
3716 return self.tk.call(
3717 (self._w, 'panecget') + (child, '-'+option))
Raymond Hettingerff41c482003-04-06 09:01:11 +00003718
Martin v. Löwis2ec36272002-10-13 10:22:08 +00003719 def paneconfigure(self, tagOrId, cnf=None, **kw):
Raymond Hettingerff41c482003-04-06 09:01:11 +00003720 """Query or modify the management options for window.
3721
Martin v. Löwis2ec36272002-10-13 10:22:08 +00003722 If no option is specified, returns a list describing all
Raymond Hettingerff41c482003-04-06 09:01:11 +00003723 of the available options for pathName. If option is
3724 specified with no value, then the command returns a list
3725 describing the one named option (this list will be identical
3726 to the corresponding sublist of the value returned if no
3727 option is specified). If one or more option-value pairs are
3728 specified, then the command modifies the given widget
3729 option(s) to have the given value(s); in this case the
3730 command returns an empty string. The following options
Martin v. Löwis2ec36272002-10-13 10:22:08 +00003731 are supported:
Raymond Hettingerff41c482003-04-06 09:01:11 +00003732
Martin v. Löwis2ec36272002-10-13 10:22:08 +00003733 after window
Raymond Hettingerff41c482003-04-06 09:01:11 +00003734 Insert the window after the window specified. window
Martin v. Löwis2ec36272002-10-13 10:22:08 +00003735 should be the name of a window already managed by pathName.
3736 before window
Raymond Hettingerff41c482003-04-06 09:01:11 +00003737 Insert the window before the window specified. window
Martin v. Löwis2ec36272002-10-13 10:22:08 +00003738 should be the name of a window already managed by pathName.
3739 height size
Raymond Hettingerff41c482003-04-06 09:01:11 +00003740 Specify a height for the window. The height will be the
3741 outer dimension of the window including its border, if
3742 any. If size is an empty string, or if -height is not
3743 specified, then the height requested internally by the
3744 window will be used initially; the height may later be
3745 adjusted by the movement of sashes in the panedwindow.
Martin v. Löwis2ec36272002-10-13 10:22:08 +00003746 Size may be any value accepted by Tk_GetPixels.
3747 minsize n
Raymond Hettingerff41c482003-04-06 09:01:11 +00003748 Specifies that the size of the window cannot be made
3749 less than n. This constraint only affects the size of
3750 the widget in the paned dimension -- the x dimension
3751 for horizontal panedwindows, the y dimension for
3752 vertical panedwindows. May be any value accepted by
Martin v. Löwis2ec36272002-10-13 10:22:08 +00003753 Tk_GetPixels.
3754 padx n
Raymond Hettingerff41c482003-04-06 09:01:11 +00003755 Specifies a non-negative value indicating how much
3756 extra space to leave on each side of the window in
3757 the X-direction. The value may have any of the forms
Martin v. Löwis2ec36272002-10-13 10:22:08 +00003758 accepted by Tk_GetPixels.
3759 pady n
3760 Specifies a non-negative value indicating how much
Raymond Hettingerff41c482003-04-06 09:01:11 +00003761 extra space to leave on each side of the window in
3762 the Y-direction. The value may have any of the forms
Martin v. Löwis2ec36272002-10-13 10:22:08 +00003763 accepted by Tk_GetPixels.
3764 sticky style
Raymond Hettingerff41c482003-04-06 09:01:11 +00003765 If a window's pane is larger than the requested
3766 dimensions of the window, this option may be used
3767 to position (or stretch) the window within its pane.
3768 Style is a string that contains zero or more of the
3769 characters n, s, e or w. The string can optionally
3770 contains spaces or commas, but they are ignored. Each
3771 letter refers to a side (north, south, east, or west)
3772 that the window will "stick" to. If both n and s
3773 (or e and w) are specified, the window will be
3774 stretched to fill the entire height (or width) of
Martin v. Löwis2ec36272002-10-13 10:22:08 +00003775 its cavity.
3776 width size
Raymond Hettingerff41c482003-04-06 09:01:11 +00003777 Specify a width for the window. The width will be
3778 the outer dimension of the window including its
3779 border, if any. If size is an empty string, or
Martin v. Löwis2ec36272002-10-13 10:22:08 +00003780 if -width is not specified, then the width requested
Raymond Hettingerff41c482003-04-06 09:01:11 +00003781 internally by the window will be used initially; the
3782 width may later be adjusted by the movement of sashes
3783 in the panedwindow. Size may be any value accepted by
Martin v. Löwis2ec36272002-10-13 10:22:08 +00003784 Tk_GetPixels.
Raymond Hettingerff41c482003-04-06 09:01:11 +00003785
Martin v. Löwis2ec36272002-10-13 10:22:08 +00003786 """
3787 if cnf is None and not kw:
3788 cnf = {}
3789 for x in self.tk.split(
3790 self.tk.call(self._w,
3791 'paneconfigure', tagOrId)):
3792 cnf[x[0][1:]] = (x[0][1:],) + x[1:]
3793 return cnf
Guido van Rossum13257902007-06-07 23:15:56 +00003794 if isinstance(cnf, str) and not kw:
Martin v. Löwis2ec36272002-10-13 10:22:08 +00003795 x = self.tk.split(self.tk.call(
3796 self._w, 'paneconfigure', tagOrId, '-'+cnf))
3797 return (x[0][1:],) + x[1:]
3798 self.tk.call((self._w, 'paneconfigure', tagOrId) +
3799 self._options(cnf, kw))
3800 paneconfig = paneconfigure
3801
3802 def panes(self):
3803 """Returns an ordered list of the child panes."""
3804 return self.tk.call(self._w, 'panes')
3805
Guido van Rossumaec5dc91994-06-27 07:55:12 +00003806######################################################################
3807# Extensions:
3808
3809class Studbutton(Button):
Fredrik Lundh06d28152000-08-09 18:03:12 +00003810 def __init__(self, master=None, cnf={}, **kw):
3811 Widget.__init__(self, master, 'studbutton', cnf, kw)
3812 self.bind('<Any-Enter>', self.tkButtonEnter)
3813 self.bind('<Any-Leave>', self.tkButtonLeave)
3814 self.bind('<1>', self.tkButtonDown)
3815 self.bind('<ButtonRelease-1>', self.tkButtonUp)
Guido van Rossumaec5dc91994-06-27 07:55:12 +00003816
3817class Tributton(Button):
Fredrik Lundh06d28152000-08-09 18:03:12 +00003818 def __init__(self, master=None, cnf={}, **kw):
3819 Widget.__init__(self, master, 'tributton', cnf, kw)
3820 self.bind('<Any-Enter>', self.tkButtonEnter)
3821 self.bind('<Any-Leave>', self.tkButtonLeave)
3822 self.bind('<1>', self.tkButtonDown)
3823 self.bind('<ButtonRelease-1>', self.tkButtonUp)
3824 self['fg'] = self['bg']
3825 self['activebackground'] = self['bg']
Guido van Rossum37dcab11996-05-16 16:00:19 +00003826
Guido van Rossumc417ef81996-08-21 23:38:59 +00003827######################################################################
3828# Test:
3829
3830def _test():
Fredrik Lundh06d28152000-08-09 18:03:12 +00003831 root = Tk()
3832 text = "This is Tcl/Tk version %s" % TclVersion
3833 if TclVersion >= 8.1:
Walter Dörwald5de48bd2007-06-11 21:38:39 +00003834 text += "\nThis should be a cedilla: \xe7"
Fredrik Lundh06d28152000-08-09 18:03:12 +00003835 label = Label(root, text=text)
3836 label.pack()
3837 test = Button(root, text="Click me!",
3838 command=lambda root=root: root.test.configure(
3839 text="[%s]" % root.test['text']))
3840 test.pack()
3841 root.test = test
3842 quit = Button(root, text="QUIT", command=root.destroy)
3843 quit.pack()
3844 # The following three commands are needed so the window pops
3845 # up on top on Windows...
3846 root.iconify()
3847 root.update()
3848 root.deiconify()
3849 root.mainloop()
Guido van Rossumc417ef81996-08-21 23:38:59 +00003850
3851if __name__ == '__main__':
Fredrik Lundh06d28152000-08-09 18:03:12 +00003852 _test()