blob: 73fca8fb45b8b13ed20eb9f0bfceacb92614b5cb [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)
Serhiy Storchakad97c01f2013-12-26 20:06:05 +0200223 elif not self._tk.getboolean(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."""
Serhiy Storchakad97c01f2013-12-26 20:06:05 +0200227 if (self._tk is not None and
228 self._tk.getboolean(self._tk.call("info", "exists", self._name))):
Martin v. Löwis2b695a42012-03-12 17:47:35 -0700229 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)
Serhiy Storchaka848972c2013-12-25 16:35:38 +02001238
1239 def _getconfigure(self, *args):
1240 """Call Tcl configure command and return the result as a dict."""
1241 cnf = {}
1242 for x in self.tk.splitlist(self.tk.call(*args)):
1243 x = self.tk.splitlist(x)
1244 cnf[x[0][1:]] = (x[0][1:],) + x[1:]
1245 return cnf
1246
1247 def _getconfigure1(self, *args):
1248 x = self.tk.splitlist(self.tk.call(*args))
1249 return (x[0][1:],) + x[1:]
1250
Martin v. Löwis6ce13152002-10-10 14:36:13 +00001251 def _configure(self, cmd, cnf, kw):
1252 """Internal function."""
1253 if kw:
1254 cnf = _cnfmerge((cnf, kw))
1255 elif cnf:
1256 cnf = _cnfmerge(cnf)
1257 if cnf is None:
Serhiy Storchaka848972c2013-12-25 16:35:38 +02001258 return self._getconfigure(_flatten((self._w, cmd)))
Guido van Rossum13257902007-06-07 23:15:56 +00001259 if isinstance(cnf, str):
Serhiy Storchaka848972c2013-12-25 16:35:38 +02001260 return self._getconfigure1(_flatten((self._w, cmd, '-'+cnf)))
Martin v. Löwis6ce13152002-10-10 14:36:13 +00001261 self.tk.call(_flatten((self._w, cmd)) + self._options(cnf))
Fredrik Lundh06d28152000-08-09 18:03:12 +00001262 # These used to be defined in Widget:
1263 def configure(self, cnf=None, **kw):
1264 """Configure resources of a widget.
Barry Warsaw107e6231998-12-15 00:44:15 +00001265
Fredrik Lundh06d28152000-08-09 18:03:12 +00001266 The values for resources are specified as keyword
1267 arguments. To get an overview about
1268 the allowed keyword arguments call the method keys.
1269 """
Martin v. Löwis6ce13152002-10-10 14:36:13 +00001270 return self._configure('configure', cnf, kw)
Fredrik Lundh06d28152000-08-09 18:03:12 +00001271 config = configure
1272 def cget(self, key):
1273 """Return the resource value for a KEY given as string."""
1274 return self.tk.call(self._w, 'cget', '-' + key)
1275 __getitem__ = cget
1276 def __setitem__(self, key, value):
1277 self.configure({key: value})
1278 def keys(self):
1279 """Return a list of all resource names of this widget."""
Alexander Belopolsky022f0492010-11-22 19:40:51 +00001280 return [x[0][1:] for x in
Serhiy Storchaka848972c2013-12-25 16:35:38 +02001281 self.tk.splitlist(self.tk.call(self._w, 'configure'))]
Fredrik Lundh06d28152000-08-09 18:03:12 +00001282 def __str__(self):
1283 """Return the window path name of this widget."""
1284 return self._w
1285 # Pack methods that apply to the master
1286 _noarg_ = ['_noarg_']
1287 def pack_propagate(self, flag=_noarg_):
1288 """Set or get the status for propagation of geometry information.
Guido van Rossum5917ecb2000-06-29 16:30:50 +00001289
Fredrik Lundh06d28152000-08-09 18:03:12 +00001290 A boolean argument specifies whether the geometry information
1291 of the slaves will determine the size of this widget. If no argument
1292 is given the current setting will be returned.
1293 """
1294 if flag is Misc._noarg_:
1295 return self._getboolean(self.tk.call(
1296 'pack', 'propagate', self._w))
1297 else:
1298 self.tk.call('pack', 'propagate', self._w, flag)
1299 propagate = pack_propagate
1300 def pack_slaves(self):
1301 """Return a list of all slaves of this widget
1302 in its packing order."""
Alexander Belopolsky022f0492010-11-22 19:40:51 +00001303 return [self._nametowidget(x) for x in
1304 self.tk.splitlist(
1305 self.tk.call('pack', 'slaves', self._w))]
Fredrik Lundh06d28152000-08-09 18:03:12 +00001306 slaves = pack_slaves
1307 # Place method that applies to the master
1308 def place_slaves(self):
1309 """Return a list of all slaves of this widget
1310 in its packing order."""
Alexander Belopolsky022f0492010-11-22 19:40:51 +00001311 return [self._nametowidget(x) for x in
1312 self.tk.splitlist(
Fredrik Lundh06d28152000-08-09 18:03:12 +00001313 self.tk.call(
Alexander Belopolsky022f0492010-11-22 19:40:51 +00001314 'place', 'slaves', self._w))]
Fredrik Lundh06d28152000-08-09 18:03:12 +00001315 # Grid methods that apply to the master
Martin v. Löwis5c3c4242012-03-13 13:40:42 -07001316 def grid_anchor(self, anchor=None): # new in Tk 8.5
1317 """The anchor value controls how to place the grid within the
1318 master when no row/column has any weight.
1319
1320 The default anchor is nw."""
1321 self.tk.call('grid', 'anchor', self._w, anchor)
1322 anchor = grid_anchor
Fredrik Lundh06d28152000-08-09 18:03:12 +00001323 def grid_bbox(self, column=None, row=None, col2=None, row2=None):
1324 """Return a tuple of integer coordinates for the bounding
1325 box of this widget controlled by the geometry manager grid.
Guido van Rossum5917ecb2000-06-29 16:30:50 +00001326
Fredrik Lundh06d28152000-08-09 18:03:12 +00001327 If COLUMN, ROW is given the bounding box applies from
1328 the cell with row and column 0 to the specified
1329 cell. If COL2 and ROW2 are given the bounding box
1330 starts at that cell.
Guido van Rossum5917ecb2000-06-29 16:30:50 +00001331
Fredrik Lundh06d28152000-08-09 18:03:12 +00001332 The returned integers specify the offset of the upper left
1333 corner in the master widget and the width and height.
1334 """
1335 args = ('grid', 'bbox', self._w)
1336 if column is not None and row is not None:
1337 args = args + (column, row)
1338 if col2 is not None and row2 is not None:
1339 args = args + (col2, row2)
Raymond Hettingerff41c482003-04-06 09:01:11 +00001340 return self._getints(self.tk.call(*args)) or None
Fredrik Lundh06d28152000-08-09 18:03:12 +00001341 bbox = grid_bbox
1342 def _grid_configure(self, command, index, cnf, kw):
1343 """Internal function."""
Guido van Rossum13257902007-06-07 23:15:56 +00001344 if isinstance(cnf, str) and not kw:
Fredrik Lundh06d28152000-08-09 18:03:12 +00001345 if cnf[-1:] == '_':
1346 cnf = cnf[:-1]
1347 if cnf[:1] != '-':
1348 cnf = '-'+cnf
1349 options = (cnf,)
1350 else:
1351 options = self._options(cnf, kw)
1352 if not options:
1353 res = self.tk.call('grid',
1354 command, self._w, index)
1355 words = self.tk.splitlist(res)
1356 dict = {}
1357 for i in range(0, len(words), 2):
1358 key = words[i][1:]
1359 value = words[i+1]
1360 if not value:
1361 value = None
Serhiy Storchaka06ce0772013-08-22 17:51:58 +03001362 elif '.' in str(value):
Fredrik Lundh06d28152000-08-09 18:03:12 +00001363 value = getdouble(value)
1364 else:
1365 value = getint(value)
1366 dict[key] = value
1367 return dict
1368 res = self.tk.call(
1369 ('grid', command, self._w, index)
1370 + options)
1371 if len(options) == 1:
1372 if not res: return None
1373 # In Tk 7.5, -width can be a float
1374 if '.' in res: return getdouble(res)
1375 return getint(res)
1376 def grid_columnconfigure(self, index, cnf={}, **kw):
1377 """Configure column INDEX of a grid.
Guido van Rossum80f8be81997-12-02 19:51:39 +00001378
Fredrik Lundh06d28152000-08-09 18:03:12 +00001379 Valid resources are minsize (minimum size of the column),
1380 weight (how much does additional space propagate to this column)
1381 and pad (how much space to let additionally)."""
1382 return self._grid_configure('columnconfigure', index, cnf, kw)
1383 columnconfigure = grid_columnconfigure
Martin v. Löwisdc579092001-10-13 09:33:51 +00001384 def grid_location(self, x, y):
1385 """Return a tuple of column and row which identify the cell
1386 at which the pixel at position X and Y inside the master
1387 widget is located."""
1388 return self._getints(
1389 self.tk.call(
1390 'grid', 'location', self._w, x, y)) or None
Fredrik Lundh06d28152000-08-09 18:03:12 +00001391 def grid_propagate(self, flag=_noarg_):
1392 """Set or get the status for propagation of geometry information.
Guido van Rossum80f8be81997-12-02 19:51:39 +00001393
Fredrik Lundh06d28152000-08-09 18:03:12 +00001394 A boolean argument specifies whether the geometry information
1395 of the slaves will determine the size of this widget. If no argument
1396 is given, the current setting will be returned.
1397 """
1398 if flag is Misc._noarg_:
1399 return self._getboolean(self.tk.call(
1400 'grid', 'propagate', self._w))
1401 else:
1402 self.tk.call('grid', 'propagate', self._w, flag)
1403 def grid_rowconfigure(self, index, cnf={}, **kw):
1404 """Configure row INDEX of a grid.
Guido van Rossum80f8be81997-12-02 19:51:39 +00001405
Fredrik Lundh06d28152000-08-09 18:03:12 +00001406 Valid resources are minsize (minimum size of the row),
1407 weight (how much does additional space propagate to this row)
1408 and pad (how much space to let additionally)."""
1409 return self._grid_configure('rowconfigure', index, cnf, kw)
1410 rowconfigure = grid_rowconfigure
1411 def grid_size(self):
1412 """Return a tuple of the number of column and rows in the grid."""
1413 return self._getints(
1414 self.tk.call('grid', 'size', self._w)) or None
1415 size = grid_size
1416 def grid_slaves(self, row=None, column=None):
1417 """Return a list of all slaves of this widget
1418 in its packing order."""
1419 args = ()
1420 if row is not None:
1421 args = args + ('-row', row)
1422 if column is not None:
1423 args = args + ('-column', column)
Alexander Belopolsky022f0492010-11-22 19:40:51 +00001424 return [self._nametowidget(x) for x in
1425 self.tk.splitlist(self.tk.call(
1426 ('grid', 'slaves', self._w) + args))]
Guido van Rossum80f8be81997-12-02 19:51:39 +00001427
Fredrik Lundh06d28152000-08-09 18:03:12 +00001428 # Support for the "event" command, new in Tk 4.2.
1429 # By Case Roole.
Guido van Rossum80f8be81997-12-02 19:51:39 +00001430
Fredrik Lundh06d28152000-08-09 18:03:12 +00001431 def event_add(self, virtual, *sequences):
1432 """Bind a virtual event VIRTUAL (of the form <<Name>>)
1433 to an event SEQUENCE such that the virtual event is triggered
1434 whenever SEQUENCE occurs."""
1435 args = ('event', 'add', virtual) + sequences
1436 self.tk.call(args)
Guido van Rossumc2966511998-04-10 19:16:10 +00001437
Fredrik Lundh06d28152000-08-09 18:03:12 +00001438 def event_delete(self, virtual, *sequences):
1439 """Unbind a virtual event VIRTUAL from SEQUENCE."""
1440 args = ('event', 'delete', virtual) + sequences
1441 self.tk.call(args)
Guido van Rossumc2966511998-04-10 19:16:10 +00001442
Fredrik Lundh06d28152000-08-09 18:03:12 +00001443 def event_generate(self, sequence, **kw):
1444 """Generate an event SEQUENCE. Additional
1445 keyword arguments specify parameter of the event
1446 (e.g. x, y, rootx, rooty)."""
1447 args = ('event', 'generate', self._w, sequence)
1448 for k, v in kw.items():
1449 args = args + ('-%s' % k, str(v))
1450 self.tk.call(args)
1451
1452 def event_info(self, virtual=None):
1453 """Return a list of all virtual events or the information
1454 about the SEQUENCE bound to the virtual event VIRTUAL."""
1455 return self.tk.splitlist(
1456 self.tk.call('event', 'info', virtual))
1457
1458 # Image related commands
1459
1460 def image_names(self):
1461 """Return a list of all existing image names."""
1462 return self.tk.call('image', 'names')
1463
1464 def image_types(self):
1465 """Return a list of all available image types (e.g. phote bitmap)."""
1466 return self.tk.call('image', 'types')
Guido van Rossumc2966511998-04-10 19:16:10 +00001467
Guido van Rossum80f8be81997-12-02 19:51:39 +00001468
Guido van Rossuma5773dd1995-09-07 19:22:00 +00001469class CallWrapper:
Fredrik Lundh06d28152000-08-09 18:03:12 +00001470 """Internal class. Stores function to call when some user
1471 defined Tcl function is called e.g. after an event occurred."""
1472 def __init__(self, func, subst, widget):
1473 """Store FUNC, SUBST and WIDGET as members."""
1474 self.func = func
1475 self.subst = subst
1476 self.widget = widget
1477 def __call__(self, *args):
1478 """Apply first function SUBST to arguments, than FUNC."""
1479 try:
1480 if self.subst:
Raymond Hettingerff41c482003-04-06 09:01:11 +00001481 args = self.subst(*args)
1482 return self.func(*args)
Andrew Svetloveb0abce2012-12-03 16:13:07 +02001483 except SystemExit:
1484 raise
Fredrik Lundh06d28152000-08-09 18:03:12 +00001485 except:
1486 self.widget._report_exception()
Guido van Rossum18468821994-06-20 07:49:28 +00001487
Guido van Rossume365a591998-05-01 19:48:20 +00001488
Guilherme Polo1fff0082009-08-14 15:05:30 +00001489class XView:
1490 """Mix-in class for querying and changing the horizontal position
1491 of a widget's window."""
1492
1493 def xview(self, *args):
1494 """Query and change the horizontal position of the view."""
1495 res = self.tk.call(self._w, 'xview', *args)
1496 if not args:
1497 return self._getdoubles(res)
1498
1499 def xview_moveto(self, fraction):
1500 """Adjusts the view in the window so that FRACTION of the
1501 total width of the canvas is off-screen to the left."""
1502 self.tk.call(self._w, 'xview', 'moveto', fraction)
1503
1504 def xview_scroll(self, number, what):
1505 """Shift the x-view according to NUMBER which is measured in "units"
1506 or "pages" (WHAT)."""
1507 self.tk.call(self._w, 'xview', 'scroll', number, what)
1508
1509
1510class YView:
1511 """Mix-in class for querying and changing the vertical position
1512 of a widget's window."""
1513
1514 def yview(self, *args):
1515 """Query and change the vertical position of the view."""
1516 res = self.tk.call(self._w, 'yview', *args)
1517 if not args:
1518 return self._getdoubles(res)
1519
1520 def yview_moveto(self, fraction):
1521 """Adjusts the view in the window so that FRACTION of the
1522 total height of the canvas is off-screen to the top."""
1523 self.tk.call(self._w, 'yview', 'moveto', fraction)
1524
1525 def yview_scroll(self, number, what):
1526 """Shift the y-view according to NUMBER which is measured in
1527 "units" or "pages" (WHAT)."""
1528 self.tk.call(self._w, 'yview', 'scroll', number, what)
1529
1530
Guido van Rossum18468821994-06-20 07:49:28 +00001531class Wm:
Fredrik Lundh06d28152000-08-09 18:03:12 +00001532 """Provides functions for the communication with the window manager."""
Raymond Hettingerff41c482003-04-06 09:01:11 +00001533
Fredrik Lundh06d28152000-08-09 18:03:12 +00001534 def wm_aspect(self,
1535 minNumer=None, minDenom=None,
1536 maxNumer=None, maxDenom=None):
1537 """Instruct the window manager to set the aspect ratio (width/height)
1538 of this widget to be between MINNUMER/MINDENOM and MAXNUMER/MAXDENOM. Return a tuple
1539 of the actual values if no argument is given."""
1540 return self._getints(
1541 self.tk.call('wm', 'aspect', self._w,
1542 minNumer, minDenom,
1543 maxNumer, maxDenom))
1544 aspect = wm_aspect
Raymond Hettingerff41c482003-04-06 09:01:11 +00001545
Martin v. Löwis2ec36272002-10-13 10:22:08 +00001546 def wm_attributes(self, *args):
1547 """This subcommand returns or sets platform specific attributes
Raymond Hettingerff41c482003-04-06 09:01:11 +00001548
1549 The first form returns a list of the platform specific flags and
1550 their values. The second form returns the value for the specific
Martin v. Löwis2ec36272002-10-13 10:22:08 +00001551 option. The third form sets one or more of the values. The values
1552 are as follows:
Raymond Hettingerff41c482003-04-06 09:01:11 +00001553
1554 On Windows, -disabled gets or sets whether the window is in a
Martin v. Löwis2ec36272002-10-13 10:22:08 +00001555 disabled state. -toolwindow gets or sets the style of the window
Raymond Hettingerff41c482003-04-06 09:01:11 +00001556 to toolwindow (as defined in the MSDN). -topmost gets or sets
1557 whether this is a topmost window (displays above all other
Martin v. Löwis2ec36272002-10-13 10:22:08 +00001558 windows).
Raymond Hettingerff41c482003-04-06 09:01:11 +00001559
1560 On Macintosh, XXXXX
1561
Martin v. Löwis2ec36272002-10-13 10:22:08 +00001562 On Unix, there are currently no special attribute values.
1563 """
1564 args = ('wm', 'attributes', self._w) + args
1565 return self.tk.call(args)
1566 attributes=wm_attributes
Raymond Hettingerff41c482003-04-06 09:01:11 +00001567
Fredrik Lundh06d28152000-08-09 18:03:12 +00001568 def wm_client(self, name=None):
1569 """Store NAME in WM_CLIENT_MACHINE property of this widget. Return
1570 current value."""
1571 return self.tk.call('wm', 'client', self._w, name)
1572 client = wm_client
1573 def wm_colormapwindows(self, *wlist):
1574 """Store list of window names (WLIST) into WM_COLORMAPWINDOWS property
1575 of this widget. This list contains windows whose colormaps differ from their
1576 parents. Return current list of widgets if WLIST is empty."""
1577 if len(wlist) > 1:
1578 wlist = (wlist,) # Tk needs a list of windows here
1579 args = ('wm', 'colormapwindows', self._w) + wlist
Alexander Belopolsky022f0492010-11-22 19:40:51 +00001580 return [self._nametowidget(x) for x in self.tk.call(args)]
Fredrik Lundh06d28152000-08-09 18:03:12 +00001581 colormapwindows = wm_colormapwindows
1582 def wm_command(self, value=None):
1583 """Store VALUE in WM_COMMAND property. It is the command
1584 which shall be used to invoke the application. Return current
1585 command if VALUE is None."""
1586 return self.tk.call('wm', 'command', self._w, value)
1587 command = wm_command
1588 def wm_deiconify(self):
1589 """Deiconify this widget. If it was never mapped it will not be mapped.
1590 On Windows it will raise this widget and give it the focus."""
1591 return self.tk.call('wm', 'deiconify', self._w)
1592 deiconify = wm_deiconify
1593 def wm_focusmodel(self, model=None):
1594 """Set focus model to MODEL. "active" means that this widget will claim
1595 the focus itself, "passive" means that the window manager shall give
1596 the focus. Return current focus model if MODEL is None."""
1597 return self.tk.call('wm', 'focusmodel', self._w, model)
1598 focusmodel = wm_focusmodel
Martin v. Löwis5c3c4242012-03-13 13:40:42 -07001599 def wm_forget(self, window): # new in Tk 8.5
1600 """The window will be unmappend from the screen and will no longer
1601 be managed by wm. toplevel windows will be treated like frame
1602 windows once they are no longer managed by wm, however, the menu
1603 option configuration will be remembered and the menus will return
1604 once the widget is managed again."""
1605 self.tk.call('wm', 'forget', window)
1606 forget = wm_forget
Fredrik Lundh06d28152000-08-09 18:03:12 +00001607 def wm_frame(self):
1608 """Return identifier for decorative frame of this widget if present."""
1609 return self.tk.call('wm', 'frame', self._w)
1610 frame = wm_frame
1611 def wm_geometry(self, newGeometry=None):
1612 """Set geometry to NEWGEOMETRY of the form =widthxheight+x+y. Return
1613 current value if None is given."""
1614 return self.tk.call('wm', 'geometry', self._w, newGeometry)
1615 geometry = wm_geometry
1616 def wm_grid(self,
1617 baseWidth=None, baseHeight=None,
1618 widthInc=None, heightInc=None):
1619 """Instruct the window manager that this widget shall only be
1620 resized on grid boundaries. WIDTHINC and HEIGHTINC are the width and
1621 height of a grid unit in pixels. BASEWIDTH and BASEHEIGHT are the
1622 number of grid units requested in Tk_GeometryRequest."""
1623 return self._getints(self.tk.call(
1624 'wm', 'grid', self._w,
1625 baseWidth, baseHeight, widthInc, heightInc))
1626 grid = wm_grid
1627 def wm_group(self, pathName=None):
1628 """Set the group leader widgets for related widgets to PATHNAME. Return
1629 the group leader of this widget if None is given."""
1630 return self.tk.call('wm', 'group', self._w, pathName)
1631 group = wm_group
Thomas Wouters0e3f5912006-08-11 14:57:12 +00001632 def wm_iconbitmap(self, bitmap=None, default=None):
Fredrik Lundh06d28152000-08-09 18:03:12 +00001633 """Set bitmap for the iconified widget to BITMAP. Return
Thomas Wouters0e3f5912006-08-11 14:57:12 +00001634 the bitmap if None is given.
1635
1636 Under Windows, the DEFAULT parameter can be used to set the icon
1637 for the widget and any descendents that don't have an icon set
1638 explicitly. DEFAULT can be the relative path to a .ico file
1639 (example: root.iconbitmap(default='myicon.ico') ). See Tk
1640 documentation for more information."""
1641 if default:
1642 return self.tk.call('wm', 'iconbitmap', self._w, '-default', default)
1643 else:
1644 return self.tk.call('wm', 'iconbitmap', self._w, bitmap)
Fredrik Lundh06d28152000-08-09 18:03:12 +00001645 iconbitmap = wm_iconbitmap
1646 def wm_iconify(self):
1647 """Display widget as icon."""
1648 return self.tk.call('wm', 'iconify', self._w)
1649 iconify = wm_iconify
1650 def wm_iconmask(self, bitmap=None):
1651 """Set mask for the icon bitmap of this widget. Return the
1652 mask if None is given."""
1653 return self.tk.call('wm', 'iconmask', self._w, bitmap)
1654 iconmask = wm_iconmask
1655 def wm_iconname(self, newName=None):
1656 """Set the name of the icon for this widget. Return the name if
1657 None is given."""
1658 return self.tk.call('wm', 'iconname', self._w, newName)
1659 iconname = wm_iconname
Martin v. Löwis5c3c4242012-03-13 13:40:42 -07001660 def wm_iconphoto(self, default=False, *args): # new in Tk 8.5
1661 """Sets the titlebar icon for this window based on the named photo
1662 images passed through args. If default is True, this is applied to
1663 all future created toplevels as well.
1664
1665 The data in the images is taken as a snapshot at the time of
1666 invocation. If the images are later changed, this is not reflected
1667 to the titlebar icons. Multiple images are accepted to allow
1668 different images sizes to be provided. The window manager may scale
1669 provided icons to an appropriate size.
1670
1671 On Windows, the images are packed into a Windows icon structure.
1672 This will override an icon specified to wm_iconbitmap, and vice
1673 versa.
1674
1675 On X, the images are arranged into the _NET_WM_ICON X property,
1676 which most modern window managers support. An icon specified by
1677 wm_iconbitmap may exist simuultaneously.
1678
1679 On Macintosh, this currently does nothing."""
1680 if default:
1681 self.tk.call('wm', 'iconphoto', self._w, "-default", *args)
1682 else:
1683 self.tk.call('wm', 'iconphoto', self._w, *args)
1684 iconphoto = wm_iconphoto
Fredrik Lundh06d28152000-08-09 18:03:12 +00001685 def wm_iconposition(self, x=None, y=None):
1686 """Set the position of the icon of this widget to X and Y. Return
1687 a tuple of the current values of X and X if None is given."""
1688 return self._getints(self.tk.call(
1689 'wm', 'iconposition', self._w, x, y))
1690 iconposition = wm_iconposition
1691 def wm_iconwindow(self, pathName=None):
1692 """Set widget PATHNAME to be displayed instead of icon. Return the current
1693 value if None is given."""
1694 return self.tk.call('wm', 'iconwindow', self._w, pathName)
1695 iconwindow = wm_iconwindow
Martin v. Löwis5c3c4242012-03-13 13:40:42 -07001696 def wm_manage(self, widget): # new in Tk 8.5
1697 """The widget specified will become a stand alone top-level window.
1698 The window will be decorated with the window managers title bar,
1699 etc."""
1700 self.tk.call('wm', 'manage', widget)
1701 manage = wm_manage
Fredrik Lundh06d28152000-08-09 18:03:12 +00001702 def wm_maxsize(self, width=None, height=None):
1703 """Set max 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', 'maxsize', self._w, width, height))
1708 maxsize = wm_maxsize
1709 def wm_minsize(self, width=None, height=None):
1710 """Set min WIDTH and HEIGHT for this widget. If the window is gridded
1711 the values are given in grid units. Return the current values if None
1712 is given."""
1713 return self._getints(self.tk.call(
1714 'wm', 'minsize', self._w, width, height))
1715 minsize = wm_minsize
1716 def wm_overrideredirect(self, boolean=None):
1717 """Instruct the window manager to ignore this widget
1718 if BOOLEAN is given with 1. Return the current value if None
1719 is given."""
1720 return self._getboolean(self.tk.call(
1721 'wm', 'overrideredirect', self._w, boolean))
1722 overrideredirect = wm_overrideredirect
1723 def wm_positionfrom(self, who=None):
1724 """Instruct the window manager that the position of this widget shall
1725 be defined by the user if WHO is "user", and by its own policy if WHO is
1726 "program"."""
1727 return self.tk.call('wm', 'positionfrom', self._w, who)
1728 positionfrom = wm_positionfrom
1729 def wm_protocol(self, name=None, func=None):
1730 """Bind function FUNC to command NAME for this widget.
1731 Return the function bound to NAME if None is given. NAME could be
1732 e.g. "WM_SAVE_YOURSELF" or "WM_DELETE_WINDOW"."""
Florent Xicluna5d1155c2011-10-28 14:45:05 +02001733 if callable(func):
Fredrik Lundh06d28152000-08-09 18:03:12 +00001734 command = self._register(func)
1735 else:
1736 command = func
1737 return self.tk.call(
1738 'wm', 'protocol', self._w, name, command)
1739 protocol = wm_protocol
1740 def wm_resizable(self, width=None, height=None):
1741 """Instruct the window manager whether this width can be resized
1742 in WIDTH or HEIGHT. Both values are boolean values."""
1743 return self.tk.call('wm', 'resizable', self._w, width, height)
1744 resizable = wm_resizable
1745 def wm_sizefrom(self, who=None):
1746 """Instruct the window manager that the size of this widget shall
1747 be defined by the user if WHO is "user", and by its own policy if WHO is
1748 "program"."""
1749 return self.tk.call('wm', 'sizefrom', self._w, who)
1750 sizefrom = wm_sizefrom
Fredrik Lundh289ad8f2000-08-09 19:11:59 +00001751 def wm_state(self, newstate=None):
1752 """Query or set the state of this widget as one of normal, icon,
1753 iconic (see wm_iconwindow), withdrawn, or zoomed (Windows only)."""
1754 return self.tk.call('wm', 'state', self._w, newstate)
Fredrik Lundh06d28152000-08-09 18:03:12 +00001755 state = wm_state
1756 def wm_title(self, string=None):
1757 """Set the title of this widget."""
1758 return self.tk.call('wm', 'title', self._w, string)
1759 title = wm_title
1760 def wm_transient(self, master=None):
1761 """Instruct the window manager that this widget is transient
1762 with regard to widget MASTER."""
1763 return self.tk.call('wm', 'transient', self._w, master)
1764 transient = wm_transient
1765 def wm_withdraw(self):
1766 """Withdraw this widget from the screen such that it is unmapped
1767 and forgotten by the window manager. Re-draw it with wm_deiconify."""
1768 return self.tk.call('wm', 'withdraw', self._w)
1769 withdraw = wm_withdraw
Guido van Rossume365a591998-05-01 19:48:20 +00001770
Guido van Rossum18468821994-06-20 07:49:28 +00001771
1772class Tk(Misc, Wm):
Fredrik Lundh06d28152000-08-09 18:03:12 +00001773 """Toplevel widget of Tk which represents mostly the main window
Ezio Melotti42da6632011-03-15 05:18:48 +02001774 of an application. It has an associated Tcl interpreter."""
Fredrik Lundh06d28152000-08-09 18:03:12 +00001775 _w = '.'
Martin v. Löwis9441c072004-08-03 18:36:25 +00001776 def __init__(self, screenName=None, baseName=None, className='Tk',
1777 useTk=1, sync=0, use=None):
Fredrik Lundh06d28152000-08-09 18:03:12 +00001778 """Return a new Toplevel widget on screen SCREENNAME. A new Tcl interpreter will
1779 be created. BASENAME will be used for the identification of the profile file (see
1780 readprofile).
1781 It is constructed from sys.argv[0] without extensions if None is given. CLASSNAME
1782 is the name of the widget class."""
Fredrik Lundh06d28152000-08-09 18:03:12 +00001783 self.master = None
1784 self.children = {}
David Aschere2b4b322004-02-18 05:59:53 +00001785 self._tkloaded = 0
1786 # to avoid recursions in the getattr code in case of failure, we
1787 # ensure that self.tk is always _something_.
Tim Peters182b5ac2004-07-18 06:16:08 +00001788 self.tk = None
Fredrik Lundh06d28152000-08-09 18:03:12 +00001789 if baseName is None:
Florent Xicluna54540ec2011-11-04 08:29:17 +01001790 import os
Fredrik Lundh06d28152000-08-09 18:03:12 +00001791 baseName = os.path.basename(sys.argv[0])
1792 baseName, ext = os.path.splitext(baseName)
1793 if ext not in ('.py', '.pyc', '.pyo'):
1794 baseName = baseName + ext
David Aschere2b4b322004-02-18 05:59:53 +00001795 interactive = 0
Martin v. Löwis9441c072004-08-03 18:36:25 +00001796 self.tk = _tkinter.create(screenName, baseName, className, interactive, wantobjects, useTk, sync, use)
David Aschere2b4b322004-02-18 05:59:53 +00001797 if useTk:
1798 self._loadtk()
Antoine Pitrou7ec3a322012-12-09 14:46:18 +01001799 if not sys.flags.ignore_environment:
1800 # Issue #16248: Honor the -E flag to avoid code injection.
1801 self.readprofile(baseName, className)
David Aschere2b4b322004-02-18 05:59:53 +00001802 def loadtk(self):
1803 if not self._tkloaded:
1804 self.tk.loadtk()
1805 self._loadtk()
1806 def _loadtk(self):
1807 self._tkloaded = 1
1808 global _default_root
Fredrik Lundh06d28152000-08-09 18:03:12 +00001809 # Version sanity checks
1810 tk_version = self.tk.getvar('tk_version')
1811 if tk_version != _tkinter.TK_VERSION:
Collin Winterce36ad82007-08-30 01:19:48 +00001812 raise RuntimeError("tk.h version (%s) doesn't match libtk.a version (%s)"
1813 % (_tkinter.TK_VERSION, tk_version))
Martin v. Löwis54895972003-05-24 11:37:15 +00001814 # Under unknown circumstances, tcl_version gets coerced to float
1815 tcl_version = str(self.tk.getvar('tcl_version'))
Fredrik Lundh06d28152000-08-09 18:03:12 +00001816 if tcl_version != _tkinter.TCL_VERSION:
Collin Winterce36ad82007-08-30 01:19:48 +00001817 raise RuntimeError("tcl.h version (%s) doesn't match libtcl.a version (%s)" \
1818 % (_tkinter.TCL_VERSION, tcl_version))
Fredrik Lundh06d28152000-08-09 18:03:12 +00001819 if TkVersion < 4.0:
Collin Winterce36ad82007-08-30 01:19:48 +00001820 raise RuntimeError("Tk 4.0 or higher is required; found Tk %s"
1821 % str(TkVersion))
Martin v. Löwis4afe1542005-03-01 08:09:28 +00001822 # Create and register the tkerror and exit commands
1823 # We need to inline parts of _register here, _ register
1824 # would register differently-named commands.
1825 if self._tclCommands is None:
1826 self._tclCommands = []
Fredrik Lundh06d28152000-08-09 18:03:12 +00001827 self.tk.createcommand('tkerror', _tkerror)
1828 self.tk.createcommand('exit', _exit)
Martin v. Löwis4afe1542005-03-01 08:09:28 +00001829 self._tclCommands.append('tkerror')
1830 self._tclCommands.append('exit')
Fredrik Lundh06d28152000-08-09 18:03:12 +00001831 if _support_default_root and not _default_root:
1832 _default_root = self
1833 self.protocol("WM_DELETE_WINDOW", self.destroy)
1834 def destroy(self):
1835 """Destroy this and all descendants widgets. This will
1836 end the application of this Tcl interpreter."""
Guido van Rossumb5a755e2007-07-18 18:15:48 +00001837 for c in list(self.children.values()): c.destroy()
Fredrik Lundh06d28152000-08-09 18:03:12 +00001838 self.tk.call('destroy', self._w)
1839 Misc.destroy(self)
1840 global _default_root
1841 if _support_default_root and _default_root is self:
1842 _default_root = None
1843 def readprofile(self, baseName, className):
1844 """Internal function. It reads BASENAME.tcl and CLASSNAME.tcl into
Neal Norwitz01688022007-08-12 00:43:29 +00001845 the Tcl Interpreter and calls exec on the contents of BASENAME.py and
1846 CLASSNAME.py if such a file exists in the home directory."""
Fredrik Lundh06d28152000-08-09 18:03:12 +00001847 import os
Guido van Rossume014a132006-08-19 16:53:45 +00001848 if 'HOME' in os.environ: home = os.environ['HOME']
Fredrik Lundh06d28152000-08-09 18:03:12 +00001849 else: home = os.curdir
1850 class_tcl = os.path.join(home, '.%s.tcl' % className)
1851 class_py = os.path.join(home, '.%s.py' % className)
1852 base_tcl = os.path.join(home, '.%s.tcl' % baseName)
1853 base_py = os.path.join(home, '.%s.py' % baseName)
1854 dir = {'self': self}
Georg Brandl14fc4272008-05-17 18:39:55 +00001855 exec('from tkinter import *', dir)
Fredrik Lundh06d28152000-08-09 18:03:12 +00001856 if os.path.isfile(class_tcl):
Fredrik Lundh06d28152000-08-09 18:03:12 +00001857 self.tk.call('source', class_tcl)
1858 if os.path.isfile(class_py):
Neal Norwitz01688022007-08-12 00:43:29 +00001859 exec(open(class_py).read(), dir)
Fredrik Lundh06d28152000-08-09 18:03:12 +00001860 if os.path.isfile(base_tcl):
Fredrik Lundh06d28152000-08-09 18:03:12 +00001861 self.tk.call('source', base_tcl)
1862 if os.path.isfile(base_py):
Neal Norwitz01688022007-08-12 00:43:29 +00001863 exec(open(base_py).read(), dir)
Fredrik Lundh06d28152000-08-09 18:03:12 +00001864 def report_callback_exception(self, exc, val, tb):
1865 """Internal function. It reports exception on sys.stderr."""
Florent Xicluna54540ec2011-11-04 08:29:17 +01001866 import traceback
Fredrik Lundh06d28152000-08-09 18:03:12 +00001867 sys.stderr.write("Exception in Tkinter callback\n")
1868 sys.last_type = exc
1869 sys.last_value = val
1870 sys.last_traceback = tb
1871 traceback.print_exception(exc, val, tb)
David Aschere2b4b322004-02-18 05:59:53 +00001872 def __getattr__(self, attr):
1873 "Delegate attribute access to the interpreter object"
1874 return getattr(self.tk, attr)
Guido van Rossum18468821994-06-20 07:49:28 +00001875
Guido van Rossum368e06b1997-11-07 20:38:49 +00001876# Ideally, the classes Pack, Place and Grid disappear, the
1877# pack/place/grid methods are defined on the Widget class, and
1878# everybody uses w.pack_whatever(...) instead of Pack.whatever(w,
1879# ...), with pack(), place() and grid() being short for
1880# pack_configure(), place_configure() and grid_columnconfigure(), and
1881# forget() being short for pack_forget(). As a practical matter, I'm
1882# afraid that there is too much code out there that may be using the
1883# Pack, Place or Grid class, so I leave them intact -- but only as
1884# backwards compatibility features. Also note that those methods that
1885# take a master as argument (e.g. pack_propagate) have been moved to
1886# the Misc class (which now incorporates all methods common between
1887# toplevel and interior widgets). Again, for compatibility, these are
1888# copied into the Pack, Place or Grid class.
1889
David Aschere2b4b322004-02-18 05:59:53 +00001890
1891def Tcl(screenName=None, baseName=None, className='Tk', useTk=0):
1892 return Tk(screenName, baseName, className, useTk)
1893
Guido van Rossum18468821994-06-20 07:49:28 +00001894class Pack:
Fredrik Lundh06d28152000-08-09 18:03:12 +00001895 """Geometry manager Pack.
Guido van Rossum5917ecb2000-06-29 16:30:50 +00001896
Fredrik Lundh06d28152000-08-09 18:03:12 +00001897 Base class to use the methods pack_* in every widget."""
1898 def pack_configure(self, cnf={}, **kw):
1899 """Pack a widget in the parent widget. Use as options:
1900 after=widget - pack it after you have packed widget
1901 anchor=NSEW (or subset) - position widget according to
1902 given direction
Georg Brandlbf1eb632008-05-29 07:19:00 +00001903 before=widget - pack it before you will pack widget
Martin v. Löwisbfe175c2003-04-16 19:42:51 +00001904 expand=bool - expand widget if parent size grows
Fredrik Lundh06d28152000-08-09 18:03:12 +00001905 fill=NONE or X or Y or BOTH - fill widget if widget grows
1906 in=master - use master to contain this widget
Georg Brandlbf1eb632008-05-29 07:19:00 +00001907 in_=master - see 'in' option description
Fredrik Lundh06d28152000-08-09 18:03:12 +00001908 ipadx=amount - add internal padding in x direction
1909 ipady=amount - add internal padding in y direction
1910 padx=amount - add padding in x direction
1911 pady=amount - add padding in y direction
1912 side=TOP or BOTTOM or LEFT or RIGHT - where to add this widget.
1913 """
1914 self.tk.call(
1915 ('pack', 'configure', self._w)
1916 + self._options(cnf, kw))
1917 pack = configure = config = pack_configure
1918 def pack_forget(self):
1919 """Unmap this widget and do not use it for the packing order."""
1920 self.tk.call('pack', 'forget', self._w)
1921 forget = pack_forget
1922 def pack_info(self):
1923 """Return information about the packing options
1924 for this widget."""
1925 words = self.tk.splitlist(
1926 self.tk.call('pack', 'info', self._w))
1927 dict = {}
1928 for i in range(0, len(words), 2):
1929 key = words[i][1:]
1930 value = words[i+1]
Serhiy Storchaka06ce0772013-08-22 17:51:58 +03001931 if str(value)[:1] == '.':
Fredrik Lundh06d28152000-08-09 18:03:12 +00001932 value = self._nametowidget(value)
1933 dict[key] = value
1934 return dict
1935 info = pack_info
1936 propagate = pack_propagate = Misc.pack_propagate
1937 slaves = pack_slaves = Misc.pack_slaves
Guido van Rossum18468821994-06-20 07:49:28 +00001938
1939class Place:
Fredrik Lundh06d28152000-08-09 18:03:12 +00001940 """Geometry manager Place.
Guido van Rossum5917ecb2000-06-29 16:30:50 +00001941
Fredrik Lundh06d28152000-08-09 18:03:12 +00001942 Base class to use the methods place_* in every widget."""
1943 def place_configure(self, cnf={}, **kw):
1944 """Place a widget in the parent widget. Use as options:
Georg Brandlbf1eb632008-05-29 07:19:00 +00001945 in=master - master relative to which the widget is placed
1946 in_=master - see 'in' option description
Fredrik Lundh06d28152000-08-09 18:03:12 +00001947 x=amount - locate anchor of this widget at position x of master
1948 y=amount - locate anchor of this widget at position y of master
1949 relx=amount - locate anchor of this widget between 0.0 and 1.0
1950 relative to width of master (1.0 is right edge)
Georg Brandlbf1eb632008-05-29 07:19:00 +00001951 rely=amount - locate anchor of this widget between 0.0 and 1.0
Fredrik Lundh06d28152000-08-09 18:03:12 +00001952 relative to height of master (1.0 is bottom edge)
Georg Brandlbf1eb632008-05-29 07:19:00 +00001953 anchor=NSEW (or subset) - position anchor according to given direction
Fredrik Lundh06d28152000-08-09 18:03:12 +00001954 width=amount - width of this widget in pixel
1955 height=amount - height of this widget in pixel
1956 relwidth=amount - width of this widget between 0.0 and 1.0
1957 relative to width of master (1.0 is the same width
Georg Brandlbf1eb632008-05-29 07:19:00 +00001958 as the master)
1959 relheight=amount - height of this widget between 0.0 and 1.0
Fredrik Lundh06d28152000-08-09 18:03:12 +00001960 relative to height of master (1.0 is the same
Georg Brandlbf1eb632008-05-29 07:19:00 +00001961 height as the master)
1962 bordermode="inside" or "outside" - whether to take border width of
1963 master widget into account
1964 """
Fredrik Lundh06d28152000-08-09 18:03:12 +00001965 self.tk.call(
1966 ('place', 'configure', self._w)
1967 + self._options(cnf, kw))
1968 place = configure = config = place_configure
1969 def place_forget(self):
1970 """Unmap this widget."""
1971 self.tk.call('place', 'forget', self._w)
1972 forget = place_forget
1973 def place_info(self):
1974 """Return information about the placing options
1975 for this widget."""
1976 words = self.tk.splitlist(
1977 self.tk.call('place', 'info', self._w))
1978 dict = {}
1979 for i in range(0, len(words), 2):
1980 key = words[i][1:]
1981 value = words[i+1]
Serhiy Storchaka06ce0772013-08-22 17:51:58 +03001982 if str(value)[:1] == '.':
Fredrik Lundh06d28152000-08-09 18:03:12 +00001983 value = self._nametowidget(value)
1984 dict[key] = value
1985 return dict
1986 info = place_info
1987 slaves = place_slaves = Misc.place_slaves
Guido van Rossum18468821994-06-20 07:49:28 +00001988
Guido van Rossum37dcab11996-05-16 16:00:19 +00001989class Grid:
Fredrik Lundh06d28152000-08-09 18:03:12 +00001990 """Geometry manager Grid.
Guido van Rossum5917ecb2000-06-29 16:30:50 +00001991
Fredrik Lundh06d28152000-08-09 18:03:12 +00001992 Base class to use the methods grid_* in every widget."""
1993 # Thanks to Masazumi Yoshikawa (yosikawa@isi.edu)
1994 def grid_configure(self, cnf={}, **kw):
1995 """Position a widget in the parent widget in a grid. Use as options:
1996 column=number - use cell identified with given column (starting with 0)
1997 columnspan=number - this widget will span several columns
1998 in=master - use master to contain this widget
Georg Brandlbf1eb632008-05-29 07:19:00 +00001999 in_=master - see 'in' option description
Fredrik Lundh06d28152000-08-09 18:03:12 +00002000 ipadx=amount - add internal padding in x direction
2001 ipady=amount - add internal padding in y direction
2002 padx=amount - add padding in x direction
2003 pady=amount - add padding in y direction
2004 row=number - use cell identified with given row (starting with 0)
2005 rowspan=number - this widget will span several rows
2006 sticky=NSEW - if cell is larger on which sides will this
2007 widget stick to the cell boundary
2008 """
2009 self.tk.call(
2010 ('grid', 'configure', self._w)
2011 + self._options(cnf, kw))
2012 grid = configure = config = grid_configure
2013 bbox = grid_bbox = Misc.grid_bbox
2014 columnconfigure = grid_columnconfigure = Misc.grid_columnconfigure
2015 def grid_forget(self):
2016 """Unmap this widget."""
2017 self.tk.call('grid', 'forget', self._w)
2018 forget = grid_forget
2019 def grid_remove(self):
2020 """Unmap this widget but remember the grid options."""
2021 self.tk.call('grid', 'remove', self._w)
2022 def grid_info(self):
2023 """Return information about the options
2024 for positioning this widget in a grid."""
2025 words = self.tk.splitlist(
2026 self.tk.call('grid', 'info', self._w))
2027 dict = {}
2028 for i in range(0, len(words), 2):
2029 key = words[i][1:]
2030 value = words[i+1]
Serhiy Storchaka06ce0772013-08-22 17:51:58 +03002031 if str(value)[:1] == '.':
Fredrik Lundh06d28152000-08-09 18:03:12 +00002032 value = self._nametowidget(value)
2033 dict[key] = value
2034 return dict
2035 info = grid_info
Martin v. Löwisdc579092001-10-13 09:33:51 +00002036 location = grid_location = Misc.grid_location
Fredrik Lundh06d28152000-08-09 18:03:12 +00002037 propagate = grid_propagate = Misc.grid_propagate
2038 rowconfigure = grid_rowconfigure = Misc.grid_rowconfigure
2039 size = grid_size = Misc.grid_size
2040 slaves = grid_slaves = Misc.grid_slaves
Guido van Rossum37dcab11996-05-16 16:00:19 +00002041
Guido van Rossum368e06b1997-11-07 20:38:49 +00002042class BaseWidget(Misc):
Fredrik Lundh06d28152000-08-09 18:03:12 +00002043 """Internal class."""
2044 def _setup(self, master, cnf):
2045 """Internal function. Sets up information about children."""
2046 if _support_default_root:
2047 global _default_root
2048 if not master:
2049 if not _default_root:
2050 _default_root = Tk()
2051 master = _default_root
2052 self.master = master
2053 self.tk = master.tk
2054 name = None
Guido van Rossume014a132006-08-19 16:53:45 +00002055 if 'name' in cnf:
Fredrik Lundh06d28152000-08-09 18:03:12 +00002056 name = cnf['name']
2057 del cnf['name']
2058 if not name:
Walter Dörwald70a6b492004-02-12 17:35:32 +00002059 name = repr(id(self))
Fredrik Lundh06d28152000-08-09 18:03:12 +00002060 self._name = name
2061 if master._w=='.':
2062 self._w = '.' + name
2063 else:
2064 self._w = master._w + '.' + name
2065 self.children = {}
Guido van Rossume014a132006-08-19 16:53:45 +00002066 if self._name in self.master.children:
Fredrik Lundh06d28152000-08-09 18:03:12 +00002067 self.master.children[self._name].destroy()
2068 self.master.children[self._name] = self
2069 def __init__(self, master, widgetName, cnf={}, kw={}, extra=()):
2070 """Construct a widget with the parent widget MASTER, a name WIDGETNAME
2071 and appropriate options."""
2072 if kw:
2073 cnf = _cnfmerge((cnf, kw))
2074 self.widgetName = widgetName
2075 BaseWidget._setup(self, master, cnf)
Hirokazu Yamamotoa18424c2008-11-04 06:26:27 +00002076 if self._tclCommands is None:
2077 self._tclCommands = []
Guilherme Polob212b752008-09-04 11:21:31 +00002078 classes = [(k, v) for k, v in cnf.items() if isinstance(k, type)]
2079 for k, v in classes:
2080 del cnf[k]
Fredrik Lundh06d28152000-08-09 18:03:12 +00002081 self.tk.call(
2082 (widgetName, self._w) + extra + self._options(cnf))
2083 for k, v in classes:
2084 k.configure(self, v)
2085 def destroy(self):
2086 """Destroy this and all descendants widgets."""
Guido van Rossum992d4a32007-07-11 13:09:30 +00002087 for c in list(self.children.values()): c.destroy()
Thomas Wouters0e3f5912006-08-11 14:57:12 +00002088 self.tk.call('destroy', self._w)
Guido van Rossume014a132006-08-19 16:53:45 +00002089 if self._name in self.master.children:
Fredrik Lundh06d28152000-08-09 18:03:12 +00002090 del self.master.children[self._name]
Fredrik Lundh06d28152000-08-09 18:03:12 +00002091 Misc.destroy(self)
2092 def _do(self, name, args=()):
2093 # XXX Obsolete -- better use self.tk.call directly!
2094 return self.tk.call((self._w, name) + args)
Guido van Rossum18468821994-06-20 07:49:28 +00002095
Guido van Rossum368e06b1997-11-07 20:38:49 +00002096class Widget(BaseWidget, Pack, Place, Grid):
Fredrik Lundh06d28152000-08-09 18:03:12 +00002097 """Internal class.
Guido van Rossum5917ecb2000-06-29 16:30:50 +00002098
Fredrik Lundh06d28152000-08-09 18:03:12 +00002099 Base class for a widget which can be positioned with the geometry managers
2100 Pack, Place or Grid."""
2101 pass
Guido van Rossum368e06b1997-11-07 20:38:49 +00002102
2103class Toplevel(BaseWidget, Wm):
Fredrik Lundh06d28152000-08-09 18:03:12 +00002104 """Toplevel widget, e.g. for dialogs."""
2105 def __init__(self, master=None, cnf={}, **kw):
2106 """Construct a toplevel widget with the parent MASTER.
Guido van Rossum5917ecb2000-06-29 16:30:50 +00002107
Fredrik Lundh06d28152000-08-09 18:03:12 +00002108 Valid resource names: background, bd, bg, borderwidth, class,
2109 colormap, container, cursor, height, highlightbackground,
2110 highlightcolor, highlightthickness, menu, relief, screen, takefocus,
2111 use, visual, width."""
2112 if kw:
2113 cnf = _cnfmerge((cnf, kw))
2114 extra = ()
2115 for wmkey in ['screen', 'class_', 'class', 'visual',
2116 'colormap']:
Guido van Rossume014a132006-08-19 16:53:45 +00002117 if wmkey in cnf:
Fredrik Lundh06d28152000-08-09 18:03:12 +00002118 val = cnf[wmkey]
2119 # TBD: a hack needed because some keys
2120 # are not valid as keyword arguments
2121 if wmkey[-1] == '_': opt = '-'+wmkey[:-1]
2122 else: opt = '-'+wmkey
2123 extra = extra + (opt, val)
2124 del cnf[wmkey]
2125 BaseWidget.__init__(self, master, 'toplevel', cnf, {}, extra)
2126 root = self._root()
2127 self.iconname(root.iconname())
2128 self.title(root.title())
2129 self.protocol("WM_DELETE_WINDOW", self.destroy)
Guido van Rossum18468821994-06-20 07:49:28 +00002130
2131class Button(Widget):
Fredrik Lundh06d28152000-08-09 18:03:12 +00002132 """Button widget."""
2133 def __init__(self, master=None, cnf={}, **kw):
2134 """Construct a button widget with the parent MASTER.
Raymond Hettingerff41c482003-04-06 09:01:11 +00002135
Martin v. Löwis2ec36272002-10-13 10:22:08 +00002136 STANDARD OPTIONS
Raymond Hettingerff41c482003-04-06 09:01:11 +00002137
Martin v. Löwis2ec36272002-10-13 10:22:08 +00002138 activebackground, activeforeground, anchor,
2139 background, bitmap, borderwidth, cursor,
Raymond Hettingerff41c482003-04-06 09:01:11 +00002140 disabledforeground, font, foreground
Martin v. Löwis2ec36272002-10-13 10:22:08 +00002141 highlightbackground, highlightcolor,
Raymond Hettingerff41c482003-04-06 09:01:11 +00002142 highlightthickness, image, justify,
Martin v. Löwis2ec36272002-10-13 10:22:08 +00002143 padx, pady, relief, repeatdelay,
Raymond Hettingerff41c482003-04-06 09:01:11 +00002144 repeatinterval, takefocus, text,
Martin v. Löwis2ec36272002-10-13 10:22:08 +00002145 textvariable, underline, wraplength
Raymond Hettingerff41c482003-04-06 09:01:11 +00002146
Martin v. Löwis2ec36272002-10-13 10:22:08 +00002147 WIDGET-SPECIFIC OPTIONS
Raymond Hettingerff41c482003-04-06 09:01:11 +00002148
Martin v. Löwis2ec36272002-10-13 10:22:08 +00002149 command, compound, default, height,
2150 overrelief, state, width
2151 """
Fredrik Lundh06d28152000-08-09 18:03:12 +00002152 Widget.__init__(self, master, 'button', cnf, kw)
Raymond Hettingerff41c482003-04-06 09:01:11 +00002153
Fredrik Lundh06d28152000-08-09 18:03:12 +00002154 def tkButtonEnter(self, *dummy):
2155 self.tk.call('tkButtonEnter', self._w)
Raymond Hettingerff41c482003-04-06 09:01:11 +00002156
Fredrik Lundh06d28152000-08-09 18:03:12 +00002157 def tkButtonLeave(self, *dummy):
2158 self.tk.call('tkButtonLeave', self._w)
Raymond Hettingerff41c482003-04-06 09:01:11 +00002159
Fredrik Lundh06d28152000-08-09 18:03:12 +00002160 def tkButtonDown(self, *dummy):
2161 self.tk.call('tkButtonDown', self._w)
Raymond Hettingerff41c482003-04-06 09:01:11 +00002162
Fredrik Lundh06d28152000-08-09 18:03:12 +00002163 def tkButtonUp(self, *dummy):
2164 self.tk.call('tkButtonUp', self._w)
Raymond Hettingerff41c482003-04-06 09:01:11 +00002165
Fredrik Lundh06d28152000-08-09 18:03:12 +00002166 def tkButtonInvoke(self, *dummy):
2167 self.tk.call('tkButtonInvoke', self._w)
Raymond Hettingerff41c482003-04-06 09:01:11 +00002168
Fredrik Lundh06d28152000-08-09 18:03:12 +00002169 def flash(self):
Raymond Hettingerff41c482003-04-06 09:01:11 +00002170 """Flash the button.
2171
2172 This is accomplished by redisplaying
2173 the button several times, alternating between active and
2174 normal colors. At the end of the flash the button is left
2175 in the same normal/active state as when the command was
2176 invoked. This command is ignored if the button's state is
Martin v. Löwis2ec36272002-10-13 10:22:08 +00002177 disabled.
2178 """
Fredrik Lundh06d28152000-08-09 18:03:12 +00002179 self.tk.call(self._w, 'flash')
Raymond Hettingerff41c482003-04-06 09:01:11 +00002180
Fredrik Lundh06d28152000-08-09 18:03:12 +00002181 def invoke(self):
Raymond Hettingerff41c482003-04-06 09:01:11 +00002182 """Invoke the command associated with the button.
2183
2184 The return value is the return value from the command,
Martin v. Löwis2ec36272002-10-13 10:22:08 +00002185 or an empty string if there is no command associated with
2186 the button. This command is ignored if the button's state
2187 is disabled.
2188 """
Fredrik Lundh06d28152000-08-09 18:03:12 +00002189 return self.tk.call(self._w, 'invoke')
Guido van Rossum18468821994-06-20 07:49:28 +00002190
Guilherme Polo1fff0082009-08-14 15:05:30 +00002191class Canvas(Widget, XView, YView):
Fredrik Lundh06d28152000-08-09 18:03:12 +00002192 """Canvas widget to display graphical elements like lines or text."""
2193 def __init__(self, master=None, cnf={}, **kw):
2194 """Construct a canvas widget with the parent MASTER.
Guido van Rossum5917ecb2000-06-29 16:30:50 +00002195
Fredrik Lundh06d28152000-08-09 18:03:12 +00002196 Valid resource names: background, bd, bg, borderwidth, closeenough,
2197 confine, cursor, height, highlightbackground, highlightcolor,
2198 highlightthickness, insertbackground, insertborderwidth,
2199 insertofftime, insertontime, insertwidth, offset, relief,
2200 scrollregion, selectbackground, selectborderwidth, selectforeground,
2201 state, takefocus, width, xscrollcommand, xscrollincrement,
2202 yscrollcommand, yscrollincrement."""
2203 Widget.__init__(self, master, 'canvas', cnf, kw)
2204 def addtag(self, *args):
2205 """Internal function."""
2206 self.tk.call((self._w, 'addtag') + args)
2207 def addtag_above(self, newtag, tagOrId):
2208 """Add tag NEWTAG to all items above TAGORID."""
2209 self.addtag(newtag, 'above', tagOrId)
2210 def addtag_all(self, newtag):
2211 """Add tag NEWTAG to all items."""
2212 self.addtag(newtag, 'all')
2213 def addtag_below(self, newtag, tagOrId):
2214 """Add tag NEWTAG to all items below TAGORID."""
2215 self.addtag(newtag, 'below', tagOrId)
2216 def addtag_closest(self, newtag, x, y, halo=None, start=None):
2217 """Add tag NEWTAG to item which is closest to pixel at X, Y.
2218 If several match take the top-most.
2219 All items closer than HALO are considered overlapping (all are
2220 closests). If START is specified the next below this tag is taken."""
2221 self.addtag(newtag, 'closest', x, y, halo, start)
2222 def addtag_enclosed(self, newtag, x1, y1, x2, y2):
2223 """Add tag NEWTAG to all items in the rectangle defined
2224 by X1,Y1,X2,Y2."""
2225 self.addtag(newtag, 'enclosed', x1, y1, x2, y2)
2226 def addtag_overlapping(self, newtag, x1, y1, x2, y2):
2227 """Add tag NEWTAG to all items which overlap the rectangle
2228 defined by X1,Y1,X2,Y2."""
2229 self.addtag(newtag, 'overlapping', x1, y1, x2, y2)
2230 def addtag_withtag(self, newtag, tagOrId):
2231 """Add tag NEWTAG to all items with TAGORID."""
2232 self.addtag(newtag, 'withtag', tagOrId)
2233 def bbox(self, *args):
2234 """Return a tuple of X1,Y1,X2,Y2 coordinates for a rectangle
2235 which encloses all items with tags specified as arguments."""
2236 return self._getints(
2237 self.tk.call((self._w, 'bbox') + args)) or None
2238 def tag_unbind(self, tagOrId, sequence, funcid=None):
2239 """Unbind for all items with TAGORID for event SEQUENCE the
2240 function identified with FUNCID."""
2241 self.tk.call(self._w, 'bind', tagOrId, sequence, '')
2242 if funcid:
2243 self.deletecommand(funcid)
2244 def tag_bind(self, tagOrId, sequence=None, func=None, add=None):
2245 """Bind to all items with TAGORID at event SEQUENCE a call to function FUNC.
Guido van Rossum5917ecb2000-06-29 16:30:50 +00002246
Fredrik Lundh06d28152000-08-09 18:03:12 +00002247 An additional boolean parameter ADD specifies whether FUNC will be
2248 called additionally to the other bound function or whether it will
2249 replace the previous function. See bind for the return value."""
2250 return self._bind((self._w, 'bind', tagOrId),
2251 sequence, func, add)
2252 def canvasx(self, screenx, gridspacing=None):
2253 """Return the canvas x coordinate of pixel position SCREENX rounded
2254 to nearest multiple of GRIDSPACING units."""
2255 return getdouble(self.tk.call(
2256 self._w, 'canvasx', screenx, gridspacing))
2257 def canvasy(self, screeny, gridspacing=None):
2258 """Return the canvas y coordinate of pixel position SCREENY rounded
2259 to nearest multiple of GRIDSPACING units."""
2260 return getdouble(self.tk.call(
2261 self._w, 'canvasy', screeny, gridspacing))
2262 def coords(self, *args):
2263 """Return a list of coordinates for the item given in ARGS."""
2264 # XXX Should use _flatten on args
Alexander Belopolsky022f0492010-11-22 19:40:51 +00002265 return [getdouble(x) for x in
Guido van Rossum0bd54331998-05-19 21:18:13 +00002266 self.tk.splitlist(
Alexander Belopolsky022f0492010-11-22 19:40:51 +00002267 self.tk.call((self._w, 'coords') + args))]
Fredrik Lundh06d28152000-08-09 18:03:12 +00002268 def _create(self, itemType, args, kw): # Args: (val, val, ..., cnf={})
2269 """Internal function."""
2270 args = _flatten(args)
2271 cnf = args[-1]
Guido van Rossum13257902007-06-07 23:15:56 +00002272 if isinstance(cnf, (dict, tuple)):
Fredrik Lundh06d28152000-08-09 18:03:12 +00002273 args = args[:-1]
2274 else:
2275 cnf = {}
Raymond Hettingerff41c482003-04-06 09:01:11 +00002276 return getint(self.tk.call(
2277 self._w, 'create', itemType,
2278 *(args + self._options(cnf, kw))))
Fredrik Lundh06d28152000-08-09 18:03:12 +00002279 def create_arc(self, *args, **kw):
2280 """Create arc shaped region with coordinates x1,y1,x2,y2."""
2281 return self._create('arc', args, kw)
2282 def create_bitmap(self, *args, **kw):
2283 """Create bitmap with coordinates x1,y1."""
2284 return self._create('bitmap', args, kw)
2285 def create_image(self, *args, **kw):
2286 """Create image item with coordinates x1,y1."""
2287 return self._create('image', args, kw)
2288 def create_line(self, *args, **kw):
2289 """Create line with coordinates x1,y1,...,xn,yn."""
2290 return self._create('line', args, kw)
2291 def create_oval(self, *args, **kw):
2292 """Create oval with coordinates x1,y1,x2,y2."""
2293 return self._create('oval', args, kw)
2294 def create_polygon(self, *args, **kw):
2295 """Create polygon with coordinates x1,y1,...,xn,yn."""
2296 return self._create('polygon', args, kw)
2297 def create_rectangle(self, *args, **kw):
2298 """Create rectangle with coordinates x1,y1,x2,y2."""
2299 return self._create('rectangle', args, kw)
2300 def create_text(self, *args, **kw):
2301 """Create text with coordinates x1,y1."""
2302 return self._create('text', args, kw)
2303 def create_window(self, *args, **kw):
2304 """Create window with coordinates x1,y1,x2,y2."""
2305 return self._create('window', args, kw)
2306 def dchars(self, *args):
2307 """Delete characters of text items identified by tag or id in ARGS (possibly
2308 several times) from FIRST to LAST character (including)."""
2309 self.tk.call((self._w, 'dchars') + args)
2310 def delete(self, *args):
2311 """Delete items identified by all tag or ids contained in ARGS."""
2312 self.tk.call((self._w, 'delete') + args)
2313 def dtag(self, *args):
2314 """Delete tag or id given as last arguments in ARGS from items
2315 identified by first argument in ARGS."""
2316 self.tk.call((self._w, 'dtag') + args)
2317 def find(self, *args):
2318 """Internal function."""
2319 return self._getints(
2320 self.tk.call((self._w, 'find') + args)) or ()
2321 def find_above(self, tagOrId):
2322 """Return items above TAGORID."""
2323 return self.find('above', tagOrId)
2324 def find_all(self):
2325 """Return all items."""
2326 return self.find('all')
2327 def find_below(self, tagOrId):
2328 """Return all items below TAGORID."""
2329 return self.find('below', tagOrId)
2330 def find_closest(self, x, y, halo=None, start=None):
2331 """Return item which is closest to pixel at X, Y.
2332 If several match take the top-most.
2333 All items closer than HALO are considered overlapping (all are
2334 closests). If START is specified the next below this tag is taken."""
2335 return self.find('closest', x, y, halo, start)
2336 def find_enclosed(self, x1, y1, x2, y2):
2337 """Return all items in rectangle defined
2338 by X1,Y1,X2,Y2."""
2339 return self.find('enclosed', x1, y1, x2, y2)
2340 def find_overlapping(self, x1, y1, x2, y2):
2341 """Return all items which overlap the rectangle
2342 defined by X1,Y1,X2,Y2."""
2343 return self.find('overlapping', x1, y1, x2, y2)
2344 def find_withtag(self, tagOrId):
2345 """Return all items with TAGORID."""
2346 return self.find('withtag', tagOrId)
2347 def focus(self, *args):
2348 """Set focus to the first item specified in ARGS."""
2349 return self.tk.call((self._w, 'focus') + args)
2350 def gettags(self, *args):
2351 """Return tags associated with the first item specified in ARGS."""
2352 return self.tk.splitlist(
2353 self.tk.call((self._w, 'gettags') + args))
2354 def icursor(self, *args):
2355 """Set cursor at position POS in the item identified by TAGORID.
2356 In ARGS TAGORID must be first."""
2357 self.tk.call((self._w, 'icursor') + args)
2358 def index(self, *args):
2359 """Return position of cursor as integer in item specified in ARGS."""
2360 return getint(self.tk.call((self._w, 'index') + args))
2361 def insert(self, *args):
2362 """Insert TEXT in item TAGORID at position POS. ARGS must
2363 be TAGORID POS TEXT."""
2364 self.tk.call((self._w, 'insert') + args)
2365 def itemcget(self, tagOrId, option):
2366 """Return the resource value for an OPTION for item TAGORID."""
2367 return self.tk.call(
2368 (self._w, 'itemcget') + (tagOrId, '-'+option))
2369 def itemconfigure(self, tagOrId, cnf=None, **kw):
2370 """Configure resources of an item TAGORID.
Guido van Rossum5917ecb2000-06-29 16:30:50 +00002371
Fredrik Lundh06d28152000-08-09 18:03:12 +00002372 The values for resources are specified as keyword
2373 arguments. To get an overview about
2374 the allowed keyword arguments call the method without arguments.
2375 """
Martin v. Löwis6ce13152002-10-10 14:36:13 +00002376 return self._configure(('itemconfigure', tagOrId), cnf, kw)
Fredrik Lundh06d28152000-08-09 18:03:12 +00002377 itemconfig = itemconfigure
2378 # lower, tkraise/lift hide Misc.lower, Misc.tkraise/lift,
2379 # so the preferred name for them is tag_lower, tag_raise
2380 # (similar to tag_bind, and similar to the Text widget);
2381 # unfortunately can't delete the old ones yet (maybe in 1.6)
2382 def tag_lower(self, *args):
2383 """Lower an item TAGORID given in ARGS
2384 (optional below another item)."""
2385 self.tk.call((self._w, 'lower') + args)
2386 lower = tag_lower
2387 def move(self, *args):
2388 """Move an item TAGORID given in ARGS."""
2389 self.tk.call((self._w, 'move') + args)
2390 def postscript(self, cnf={}, **kw):
2391 """Print the contents of the canvas to a postscript
2392 file. Valid options: colormap, colormode, file, fontmap,
2393 height, pageanchor, pageheight, pagewidth, pagex, pagey,
2394 rotate, witdh, x, y."""
2395 return self.tk.call((self._w, 'postscript') +
2396 self._options(cnf, kw))
2397 def tag_raise(self, *args):
2398 """Raise an item TAGORID given in ARGS
2399 (optional above another item)."""
2400 self.tk.call((self._w, 'raise') + args)
2401 lift = tkraise = tag_raise
2402 def scale(self, *args):
2403 """Scale item TAGORID with XORIGIN, YORIGIN, XSCALE, YSCALE."""
2404 self.tk.call((self._w, 'scale') + args)
2405 def scan_mark(self, x, y):
2406 """Remember the current X, Y coordinates."""
2407 self.tk.call(self._w, 'scan', 'mark', x, y)
Neal Norwitze931ed52003-01-10 23:24:32 +00002408 def scan_dragto(self, x, y, gain=10):
2409 """Adjust the view of the canvas to GAIN times the
Fredrik Lundh06d28152000-08-09 18:03:12 +00002410 difference between X and Y and the coordinates given in
2411 scan_mark."""
Neal Norwitze931ed52003-01-10 23:24:32 +00002412 self.tk.call(self._w, 'scan', 'dragto', x, y, gain)
Fredrik Lundh06d28152000-08-09 18:03:12 +00002413 def select_adjust(self, tagOrId, index):
2414 """Adjust the end of the selection near the cursor of an item TAGORID to index."""
2415 self.tk.call(self._w, 'select', 'adjust', tagOrId, index)
2416 def select_clear(self):
2417 """Clear the selection if it is in this widget."""
2418 self.tk.call(self._w, 'select', 'clear')
2419 def select_from(self, tagOrId, index):
2420 """Set the fixed end of a selection in item TAGORID to INDEX."""
2421 self.tk.call(self._w, 'select', 'from', tagOrId, index)
2422 def select_item(self):
2423 """Return the item which has the selection."""
Neal Norwitz58b63bf2002-07-23 02:52:58 +00002424 return self.tk.call(self._w, 'select', 'item') or None
Fredrik Lundh06d28152000-08-09 18:03:12 +00002425 def select_to(self, tagOrId, index):
2426 """Set the variable end of a selection in item TAGORID to INDEX."""
2427 self.tk.call(self._w, 'select', 'to', tagOrId, index)
2428 def type(self, tagOrId):
2429 """Return the type of the item TAGORID."""
2430 return self.tk.call(self._w, 'type', tagOrId) or None
Guido van Rossum18468821994-06-20 07:49:28 +00002431
2432class Checkbutton(Widget):
Fredrik Lundh06d28152000-08-09 18:03:12 +00002433 """Checkbutton widget which is either in on- or off-state."""
2434 def __init__(self, master=None, cnf={}, **kw):
2435 """Construct a checkbutton widget with the parent MASTER.
Guido van Rossum5917ecb2000-06-29 16:30:50 +00002436
Fredrik Lundh06d28152000-08-09 18:03:12 +00002437 Valid resource names: activebackground, activeforeground, anchor,
2438 background, bd, bg, bitmap, borderwidth, command, cursor,
2439 disabledforeground, fg, font, foreground, height,
2440 highlightbackground, highlightcolor, highlightthickness, image,
2441 indicatoron, justify, offvalue, onvalue, padx, pady, relief,
2442 selectcolor, selectimage, state, takefocus, text, textvariable,
2443 underline, variable, width, wraplength."""
2444 Widget.__init__(self, master, 'checkbutton', cnf, kw)
2445 def deselect(self):
2446 """Put the button in off-state."""
2447 self.tk.call(self._w, 'deselect')
2448 def flash(self):
2449 """Flash the button."""
2450 self.tk.call(self._w, 'flash')
2451 def invoke(self):
2452 """Toggle the button and invoke a command if given as resource."""
2453 return self.tk.call(self._w, 'invoke')
2454 def select(self):
2455 """Put the button in on-state."""
2456 self.tk.call(self._w, 'select')
2457 def toggle(self):
2458 """Toggle the button."""
2459 self.tk.call(self._w, 'toggle')
Guido van Rossum18468821994-06-20 07:49:28 +00002460
Guilherme Polo1fff0082009-08-14 15:05:30 +00002461class Entry(Widget, XView):
Fredrik Lundh06d28152000-08-09 18:03:12 +00002462 """Entry widget which allows to display simple text."""
2463 def __init__(self, master=None, cnf={}, **kw):
2464 """Construct an entry widget with the parent MASTER.
Guido van Rossum5917ecb2000-06-29 16:30:50 +00002465
Fredrik Lundh06d28152000-08-09 18:03:12 +00002466 Valid resource names: background, bd, bg, borderwidth, cursor,
2467 exportselection, fg, font, foreground, highlightbackground,
2468 highlightcolor, highlightthickness, insertbackground,
2469 insertborderwidth, insertofftime, insertontime, insertwidth,
2470 invalidcommand, invcmd, justify, relief, selectbackground,
2471 selectborderwidth, selectforeground, show, state, takefocus,
2472 textvariable, validate, validatecommand, vcmd, width,
2473 xscrollcommand."""
2474 Widget.__init__(self, master, 'entry', cnf, kw)
2475 def delete(self, first, last=None):
2476 """Delete text from FIRST to LAST (not included)."""
2477 self.tk.call(self._w, 'delete', first, last)
2478 def get(self):
2479 """Return the text."""
2480 return self.tk.call(self._w, 'get')
2481 def icursor(self, index):
2482 """Insert cursor at INDEX."""
2483 self.tk.call(self._w, 'icursor', index)
2484 def index(self, index):
2485 """Return position of cursor."""
2486 return getint(self.tk.call(
2487 self._w, 'index', index))
2488 def insert(self, index, string):
2489 """Insert STRING at INDEX."""
2490 self.tk.call(self._w, 'insert', index, string)
2491 def scan_mark(self, x):
2492 """Remember the current X, Y coordinates."""
2493 self.tk.call(self._w, 'scan', 'mark', x)
2494 def scan_dragto(self, x):
2495 """Adjust the view of the canvas to 10 times the
2496 difference between X and Y and the coordinates given in
2497 scan_mark."""
2498 self.tk.call(self._w, 'scan', 'dragto', x)
2499 def selection_adjust(self, index):
2500 """Adjust the end of the selection near the cursor to INDEX."""
2501 self.tk.call(self._w, 'selection', 'adjust', index)
2502 select_adjust = selection_adjust
2503 def selection_clear(self):
2504 """Clear the selection if it is in this widget."""
2505 self.tk.call(self._w, 'selection', 'clear')
2506 select_clear = selection_clear
2507 def selection_from(self, index):
2508 """Set the fixed end of a selection to INDEX."""
2509 self.tk.call(self._w, 'selection', 'from', index)
2510 select_from = selection_from
2511 def selection_present(self):
Guilherme Polo1fff0082009-08-14 15:05:30 +00002512 """Return True if there are characters selected in the entry, False
2513 otherwise."""
Fredrik Lundh06d28152000-08-09 18:03:12 +00002514 return self.tk.getboolean(
2515 self.tk.call(self._w, 'selection', 'present'))
2516 select_present = selection_present
2517 def selection_range(self, start, end):
2518 """Set the selection from START to END (not included)."""
2519 self.tk.call(self._w, 'selection', 'range', start, end)
2520 select_range = selection_range
2521 def selection_to(self, index):
2522 """Set the variable end of a selection to INDEX."""
2523 self.tk.call(self._w, 'selection', 'to', index)
2524 select_to = selection_to
Guido van Rossum18468821994-06-20 07:49:28 +00002525
2526class Frame(Widget):
Fredrik Lundh06d28152000-08-09 18:03:12 +00002527 """Frame widget which may contain other widgets and can have a 3D border."""
2528 def __init__(self, master=None, cnf={}, **kw):
2529 """Construct a frame widget with the parent MASTER.
Guido van Rossum5917ecb2000-06-29 16:30:50 +00002530
Fredrik Lundh06d28152000-08-09 18:03:12 +00002531 Valid resource names: background, bd, bg, borderwidth, class,
2532 colormap, container, cursor, height, highlightbackground,
2533 highlightcolor, highlightthickness, relief, takefocus, visual, width."""
2534 cnf = _cnfmerge((cnf, kw))
2535 extra = ()
Guido van Rossume014a132006-08-19 16:53:45 +00002536 if 'class_' in cnf:
Fredrik Lundh06d28152000-08-09 18:03:12 +00002537 extra = ('-class', cnf['class_'])
2538 del cnf['class_']
Guido van Rossume014a132006-08-19 16:53:45 +00002539 elif 'class' in cnf:
Fredrik Lundh06d28152000-08-09 18:03:12 +00002540 extra = ('-class', cnf['class'])
2541 del cnf['class']
2542 Widget.__init__(self, master, 'frame', cnf, {}, extra)
Guido van Rossum18468821994-06-20 07:49:28 +00002543
2544class Label(Widget):
Fredrik Lundh06d28152000-08-09 18:03:12 +00002545 """Label widget which can display text and bitmaps."""
2546 def __init__(self, master=None, cnf={}, **kw):
2547 """Construct a label widget with the parent MASTER.
Raymond Hettingerff41c482003-04-06 09:01:11 +00002548
Martin v. Löwis2ec36272002-10-13 10:22:08 +00002549 STANDARD OPTIONS
Raymond Hettingerff41c482003-04-06 09:01:11 +00002550
2551 activebackground, activeforeground, anchor,
2552 background, bitmap, borderwidth, cursor,
Martin v. Löwis2ec36272002-10-13 10:22:08 +00002553 disabledforeground, font, foreground,
Raymond Hettingerff41c482003-04-06 09:01:11 +00002554 highlightbackground, highlightcolor,
2555 highlightthickness, image, justify,
2556 padx, pady, relief, takefocus, text,
Martin v. Löwis2ec36272002-10-13 10:22:08 +00002557 textvariable, underline, wraplength
Raymond Hettingerff41c482003-04-06 09:01:11 +00002558
Martin v. Löwis2ec36272002-10-13 10:22:08 +00002559 WIDGET-SPECIFIC OPTIONS
Raymond Hettingerff41c482003-04-06 09:01:11 +00002560
Martin v. Löwis2ec36272002-10-13 10:22:08 +00002561 height, state, width
Raymond Hettingerff41c482003-04-06 09:01:11 +00002562
Martin v. Löwis2ec36272002-10-13 10:22:08 +00002563 """
Fredrik Lundh06d28152000-08-09 18:03:12 +00002564 Widget.__init__(self, master, 'label', cnf, kw)
Guido van Rossum761c5ab1995-07-14 15:29:10 +00002565
Guilherme Polo1fff0082009-08-14 15:05:30 +00002566class Listbox(Widget, XView, YView):
Fredrik Lundh06d28152000-08-09 18:03:12 +00002567 """Listbox widget which can display a list of strings."""
2568 def __init__(self, master=None, cnf={}, **kw):
2569 """Construct a listbox widget with the parent MASTER.
Guido van Rossum5917ecb2000-06-29 16:30:50 +00002570
Fredrik Lundh06d28152000-08-09 18:03:12 +00002571 Valid resource names: background, bd, bg, borderwidth, cursor,
2572 exportselection, fg, font, foreground, height, highlightbackground,
2573 highlightcolor, highlightthickness, relief, selectbackground,
2574 selectborderwidth, selectforeground, selectmode, setgrid, takefocus,
2575 width, xscrollcommand, yscrollcommand, listvariable."""
2576 Widget.__init__(self, master, 'listbox', cnf, kw)
2577 def activate(self, index):
2578 """Activate item identified by INDEX."""
2579 self.tk.call(self._w, 'activate', index)
2580 def bbox(self, *args):
2581 """Return a tuple of X1,Y1,X2,Y2 coordinates for a rectangle
2582 which encloses the item identified by index in ARGS."""
2583 return self._getints(
2584 self.tk.call((self._w, 'bbox') + args)) or None
2585 def curselection(self):
2586 """Return list of indices of currently selected item."""
2587 # XXX Ought to apply self._getints()...
2588 return self.tk.splitlist(self.tk.call(
2589 self._w, 'curselection'))
2590 def delete(self, first, last=None):
2591 """Delete items from FIRST to LAST (not included)."""
2592 self.tk.call(self._w, 'delete', first, last)
2593 def get(self, first, last=None):
2594 """Get list of items from FIRST to LAST (not included)."""
2595 if last:
2596 return self.tk.splitlist(self.tk.call(
2597 self._w, 'get', first, last))
2598 else:
2599 return self.tk.call(self._w, 'get', first)
2600 def index(self, index):
2601 """Return index of item identified with INDEX."""
2602 i = self.tk.call(self._w, 'index', index)
2603 if i == 'none': return None
2604 return getint(i)
2605 def insert(self, index, *elements):
2606 """Insert ELEMENTS at INDEX."""
2607 self.tk.call((self._w, 'insert', index) + elements)
2608 def nearest(self, y):
2609 """Get index of item which is nearest to y coordinate Y."""
2610 return getint(self.tk.call(
2611 self._w, 'nearest', y))
2612 def scan_mark(self, x, y):
2613 """Remember the current X, Y coordinates."""
2614 self.tk.call(self._w, 'scan', 'mark', x, y)
2615 def scan_dragto(self, x, y):
2616 """Adjust the view of the listbox to 10 times the
2617 difference between X and Y and the coordinates given in
2618 scan_mark."""
2619 self.tk.call(self._w, 'scan', 'dragto', x, y)
2620 def see(self, index):
2621 """Scroll such that INDEX is visible."""
2622 self.tk.call(self._w, 'see', index)
2623 def selection_anchor(self, index):
2624 """Set the fixed end oft the selection to INDEX."""
2625 self.tk.call(self._w, 'selection', 'anchor', index)
2626 select_anchor = selection_anchor
2627 def selection_clear(self, first, last=None):
2628 """Clear the selection from FIRST to LAST (not included)."""
2629 self.tk.call(self._w,
2630 'selection', 'clear', first, last)
2631 select_clear = selection_clear
2632 def selection_includes(self, index):
2633 """Return 1 if INDEX is part of the selection."""
2634 return self.tk.getboolean(self.tk.call(
2635 self._w, 'selection', 'includes', index))
2636 select_includes = selection_includes
2637 def selection_set(self, first, last=None):
2638 """Set the selection from FIRST to LAST (not included) without
2639 changing the currently selected elements."""
2640 self.tk.call(self._w, 'selection', 'set', first, last)
2641 select_set = selection_set
2642 def size(self):
2643 """Return the number of elements in the listbox."""
2644 return getint(self.tk.call(self._w, 'size'))
Guido van Rossum09f1ad82001-09-05 19:29:56 +00002645 def itemcget(self, index, option):
2646 """Return the resource value for an ITEM and an OPTION."""
2647 return self.tk.call(
2648 (self._w, 'itemcget') + (index, '-'+option))
Guido van Rossuma0adb922001-09-01 18:29:55 +00002649 def itemconfigure(self, index, cnf=None, **kw):
Guido van Rossum09f1ad82001-09-05 19:29:56 +00002650 """Configure resources of an ITEM.
Guido van Rossuma0adb922001-09-01 18:29:55 +00002651
2652 The values for resources are specified as keyword arguments.
2653 To get an overview about the allowed keyword arguments
2654 call the method without arguments.
2655 Valid resource names: background, bg, foreground, fg,
2656 selectbackground, selectforeground."""
Martin v. Löwis6ce13152002-10-10 14:36:13 +00002657 return self._configure(('itemconfigure', index), cnf, kw)
Guido van Rossuma0adb922001-09-01 18:29:55 +00002658 itemconfig = itemconfigure
Guido van Rossum18468821994-06-20 07:49:28 +00002659
2660class Menu(Widget):
Fredrik Lundh06d28152000-08-09 18:03:12 +00002661 """Menu widget which allows to display menu bars, pull-down menus and pop-up menus."""
2662 def __init__(self, master=None, cnf={}, **kw):
2663 """Construct menu widget with the parent MASTER.
Guido van Rossum5917ecb2000-06-29 16:30:50 +00002664
Fredrik Lundh06d28152000-08-09 18:03:12 +00002665 Valid resource names: activebackground, activeborderwidth,
2666 activeforeground, background, bd, bg, borderwidth, cursor,
2667 disabledforeground, fg, font, foreground, postcommand, relief,
2668 selectcolor, takefocus, tearoff, tearoffcommand, title, type."""
2669 Widget.__init__(self, master, 'menu', cnf, kw)
2670 def tk_bindForTraversal(self):
2671 pass # obsolete since Tk 4.0
2672 def tk_mbPost(self):
2673 self.tk.call('tk_mbPost', self._w)
2674 def tk_mbUnpost(self):
2675 self.tk.call('tk_mbUnpost')
2676 def tk_traverseToMenu(self, char):
2677 self.tk.call('tk_traverseToMenu', self._w, char)
2678 def tk_traverseWithinMenu(self, char):
2679 self.tk.call('tk_traverseWithinMenu', self._w, char)
2680 def tk_getMenuButtons(self):
2681 return self.tk.call('tk_getMenuButtons', self._w)
2682 def tk_nextMenu(self, count):
2683 self.tk.call('tk_nextMenu', count)
2684 def tk_nextMenuEntry(self, count):
2685 self.tk.call('tk_nextMenuEntry', count)
2686 def tk_invokeMenu(self):
2687 self.tk.call('tk_invokeMenu', self._w)
2688 def tk_firstMenu(self):
2689 self.tk.call('tk_firstMenu', self._w)
2690 def tk_mbButtonDown(self):
2691 self.tk.call('tk_mbButtonDown', self._w)
2692 def tk_popup(self, x, y, entry=""):
2693 """Post the menu at position X,Y with entry ENTRY."""
2694 self.tk.call('tk_popup', self._w, x, y, entry)
2695 def activate(self, index):
2696 """Activate entry at INDEX."""
2697 self.tk.call(self._w, 'activate', index)
2698 def add(self, itemType, cnf={}, **kw):
2699 """Internal function."""
2700 self.tk.call((self._w, 'add', itemType) +
2701 self._options(cnf, kw))
2702 def add_cascade(self, cnf={}, **kw):
2703 """Add hierarchical menu item."""
2704 self.add('cascade', cnf or kw)
2705 def add_checkbutton(self, cnf={}, **kw):
2706 """Add checkbutton menu item."""
2707 self.add('checkbutton', cnf or kw)
2708 def add_command(self, cnf={}, **kw):
2709 """Add command menu item."""
2710 self.add('command', cnf or kw)
2711 def add_radiobutton(self, cnf={}, **kw):
2712 """Addd radio menu item."""
2713 self.add('radiobutton', cnf or kw)
2714 def add_separator(self, cnf={}, **kw):
2715 """Add separator."""
2716 self.add('separator', cnf or kw)
2717 def insert(self, index, itemType, cnf={}, **kw):
2718 """Internal function."""
2719 self.tk.call((self._w, 'insert', index, itemType) +
2720 self._options(cnf, kw))
2721 def insert_cascade(self, index, cnf={}, **kw):
2722 """Add hierarchical menu item at INDEX."""
2723 self.insert(index, 'cascade', cnf or kw)
2724 def insert_checkbutton(self, index, cnf={}, **kw):
2725 """Add checkbutton menu item at INDEX."""
2726 self.insert(index, 'checkbutton', cnf or kw)
2727 def insert_command(self, index, cnf={}, **kw):
2728 """Add command menu item at INDEX."""
2729 self.insert(index, 'command', cnf or kw)
2730 def insert_radiobutton(self, index, cnf={}, **kw):
2731 """Addd radio menu item at INDEX."""
2732 self.insert(index, 'radiobutton', cnf or kw)
2733 def insert_separator(self, index, cnf={}, **kw):
2734 """Add separator at INDEX."""
2735 self.insert(index, 'separator', cnf or kw)
2736 def delete(self, index1, index2=None):
Hirokazu Yamamotoa18424c2008-11-04 06:26:27 +00002737 """Delete menu items between INDEX1 and INDEX2 (included)."""
Robert Schuppenies3d1c7de2008-08-10 11:28:17 +00002738 if index2 is None:
2739 index2 = index1
Robert Schuppenies3d1c7de2008-08-10 11:28:17 +00002740
Hirokazu Yamamotoa18424c2008-11-04 06:26:27 +00002741 num_index1, num_index2 = self.index(index1), self.index(index2)
2742 if (num_index1 is None) or (num_index2 is None):
2743 num_index1, num_index2 = 0, -1
2744
2745 for i in range(num_index1, num_index2 + 1):
2746 if 'command' in self.entryconfig(i):
2747 c = str(self.entrycget(i, 'command'))
2748 if c:
2749 self.deletecommand(c)
2750 self.tk.call(self._w, 'delete', index1, index2)
Fredrik Lundh06d28152000-08-09 18:03:12 +00002751 def entrycget(self, index, option):
2752 """Return the resource value of an menu item for OPTION at INDEX."""
2753 return self.tk.call(self._w, 'entrycget', index, '-' + option)
2754 def entryconfigure(self, index, cnf=None, **kw):
2755 """Configure a menu item at INDEX."""
Martin v. Löwis6ce13152002-10-10 14:36:13 +00002756 return self._configure(('entryconfigure', index), cnf, kw)
Fredrik Lundh06d28152000-08-09 18:03:12 +00002757 entryconfig = entryconfigure
2758 def index(self, index):
2759 """Return the index of a menu item identified by INDEX."""
2760 i = self.tk.call(self._w, 'index', index)
2761 if i == 'none': return None
2762 return getint(i)
2763 def invoke(self, index):
2764 """Invoke a menu item identified by INDEX and execute
2765 the associated command."""
2766 return self.tk.call(self._w, 'invoke', index)
2767 def post(self, x, y):
2768 """Display a menu at position X,Y."""
2769 self.tk.call(self._w, 'post', x, y)
2770 def type(self, index):
2771 """Return the type of the menu item at INDEX."""
2772 return self.tk.call(self._w, 'type', index)
2773 def unpost(self):
2774 """Unmap a menu."""
2775 self.tk.call(self._w, 'unpost')
Martin v. Löwis5c3c4242012-03-13 13:40:42 -07002776 def xposition(self, index): # new in Tk 8.5
2777 """Return the x-position of the leftmost pixel of the menu item
2778 at INDEX."""
2779 return getint(self.tk.call(self._w, 'xposition', index))
Fredrik Lundh06d28152000-08-09 18:03:12 +00002780 def yposition(self, index):
2781 """Return the y-position of the topmost pixel of the menu item at INDEX."""
2782 return getint(self.tk.call(
2783 self._w, 'yposition', index))
Guido van Rossum18468821994-06-20 07:49:28 +00002784
2785class Menubutton(Widget):
Fredrik Lundh06d28152000-08-09 18:03:12 +00002786 """Menubutton widget, obsolete since Tk8.0."""
2787 def __init__(self, master=None, cnf={}, **kw):
2788 Widget.__init__(self, master, 'menubutton', cnf, kw)
Guido van Rossum18468821994-06-20 07:49:28 +00002789
2790class Message(Widget):
Fredrik Lundh06d28152000-08-09 18:03:12 +00002791 """Message widget to display multiline text. Obsolete since Label does it too."""
2792 def __init__(self, master=None, cnf={}, **kw):
2793 Widget.__init__(self, master, 'message', cnf, kw)
Guido van Rossum18468821994-06-20 07:49:28 +00002794
2795class Radiobutton(Widget):
Fredrik Lundh06d28152000-08-09 18:03:12 +00002796 """Radiobutton widget which shows only one of several buttons in on-state."""
2797 def __init__(self, master=None, cnf={}, **kw):
2798 """Construct a radiobutton widget with the parent MASTER.
Guido van Rossum5917ecb2000-06-29 16:30:50 +00002799
Fredrik Lundh06d28152000-08-09 18:03:12 +00002800 Valid resource names: activebackground, activeforeground, anchor,
2801 background, bd, bg, bitmap, borderwidth, command, cursor,
2802 disabledforeground, fg, font, foreground, height,
2803 highlightbackground, highlightcolor, highlightthickness, image,
2804 indicatoron, justify, padx, pady, relief, selectcolor, selectimage,
2805 state, takefocus, text, textvariable, underline, value, variable,
2806 width, wraplength."""
2807 Widget.__init__(self, master, 'radiobutton', cnf, kw)
2808 def deselect(self):
2809 """Put the button in off-state."""
Guido van Rossum5917ecb2000-06-29 16:30:50 +00002810
Fredrik Lundh06d28152000-08-09 18:03:12 +00002811 self.tk.call(self._w, 'deselect')
2812 def flash(self):
2813 """Flash the button."""
2814 self.tk.call(self._w, 'flash')
2815 def invoke(self):
2816 """Toggle the button and invoke a command if given as resource."""
2817 return self.tk.call(self._w, 'invoke')
2818 def select(self):
2819 """Put the button in on-state."""
2820 self.tk.call(self._w, 'select')
Guido van Rossum18468821994-06-20 07:49:28 +00002821
2822class Scale(Widget):
Fredrik Lundh06d28152000-08-09 18:03:12 +00002823 """Scale widget which can display a numerical scale."""
2824 def __init__(self, master=None, cnf={}, **kw):
2825 """Construct a scale widget with the parent MASTER.
Guido van Rossum5917ecb2000-06-29 16:30:50 +00002826
Fredrik Lundh06d28152000-08-09 18:03:12 +00002827 Valid resource names: activebackground, background, bigincrement, bd,
2828 bg, borderwidth, command, cursor, digits, fg, font, foreground, from,
2829 highlightbackground, highlightcolor, highlightthickness, label,
2830 length, orient, relief, repeatdelay, repeatinterval, resolution,
2831 showvalue, sliderlength, sliderrelief, state, takefocus,
2832 tickinterval, to, troughcolor, variable, width."""
2833 Widget.__init__(self, master, 'scale', cnf, kw)
2834 def get(self):
2835 """Get the current value as integer or float."""
2836 value = self.tk.call(self._w, 'get')
2837 try:
2838 return getint(value)
2839 except ValueError:
2840 return getdouble(value)
2841 def set(self, value):
2842 """Set the value to VALUE."""
2843 self.tk.call(self._w, 'set', value)
2844 def coords(self, value=None):
2845 """Return a tuple (X,Y) of the point along the centerline of the
2846 trough that corresponds to VALUE or the current value if None is
2847 given."""
2848
2849 return self._getints(self.tk.call(self._w, 'coords', value))
2850 def identify(self, x, y):
2851 """Return where the point X,Y lies. Valid return values are "slider",
2852 "though1" and "though2"."""
2853 return self.tk.call(self._w, 'identify', x, y)
Guido van Rossum18468821994-06-20 07:49:28 +00002854
2855class Scrollbar(Widget):
Fredrik Lundh06d28152000-08-09 18:03:12 +00002856 """Scrollbar widget which displays a slider at a certain position."""
2857 def __init__(self, master=None, cnf={}, **kw):
2858 """Construct a scrollbar widget with the parent MASTER.
Guido van Rossum5917ecb2000-06-29 16:30:50 +00002859
Fredrik Lundh06d28152000-08-09 18:03:12 +00002860 Valid resource names: activebackground, activerelief,
2861 background, bd, bg, borderwidth, command, cursor,
2862 elementborderwidth, highlightbackground,
2863 highlightcolor, highlightthickness, jump, orient,
2864 relief, repeatdelay, repeatinterval, takefocus,
2865 troughcolor, width."""
2866 Widget.__init__(self, master, 'scrollbar', cnf, kw)
2867 def activate(self, index):
2868 """Display the element at INDEX with activebackground and activerelief.
2869 INDEX can be "arrow1","slider" or "arrow2"."""
2870 self.tk.call(self._w, 'activate', index)
2871 def delta(self, deltax, deltay):
2872 """Return the fractional change of the scrollbar setting if it
2873 would be moved by DELTAX or DELTAY pixels."""
2874 return getdouble(
2875 self.tk.call(self._w, 'delta', deltax, deltay))
2876 def fraction(self, x, y):
2877 """Return the fractional value which corresponds to a slider
2878 position of X,Y."""
2879 return getdouble(self.tk.call(self._w, 'fraction', x, y))
2880 def identify(self, x, y):
2881 """Return the element under position X,Y as one of
2882 "arrow1","slider","arrow2" or ""."""
2883 return self.tk.call(self._w, 'identify', x, y)
2884 def get(self):
2885 """Return the current fractional values (upper and lower end)
2886 of the slider position."""
2887 return self._getdoubles(self.tk.call(self._w, 'get'))
2888 def set(self, *args):
2889 """Set the fractional values of the slider position (upper and
2890 lower ends as value between 0 and 1)."""
2891 self.tk.call((self._w, 'set') + args)
Raymond Hettingerff41c482003-04-06 09:01:11 +00002892
2893
2894
Guilherme Polo1fff0082009-08-14 15:05:30 +00002895class Text(Widget, XView, YView):
Fredrik Lundh06d28152000-08-09 18:03:12 +00002896 """Text widget which can display text in various forms."""
Fredrik Lundh06d28152000-08-09 18:03:12 +00002897 def __init__(self, master=None, cnf={}, **kw):
2898 """Construct a text widget with the parent MASTER.
Raymond Hettingerff41c482003-04-06 09:01:11 +00002899
Martin v. Löwis2ec36272002-10-13 10:22:08 +00002900 STANDARD OPTIONS
Raymond Hettingerff41c482003-04-06 09:01:11 +00002901
Martin v. Löwis2ec36272002-10-13 10:22:08 +00002902 background, borderwidth, cursor,
2903 exportselection, font, foreground,
2904 highlightbackground, highlightcolor,
2905 highlightthickness, insertbackground,
2906 insertborderwidth, insertofftime,
2907 insertontime, insertwidth, padx, pady,
Raymond Hettingerff41c482003-04-06 09:01:11 +00002908 relief, selectbackground,
Martin v. Löwis2ec36272002-10-13 10:22:08 +00002909 selectborderwidth, selectforeground,
Raymond Hettingerff41c482003-04-06 09:01:11 +00002910 setgrid, takefocus,
Martin v. Löwis2ec36272002-10-13 10:22:08 +00002911 xscrollcommand, yscrollcommand,
Guido van Rossum5917ecb2000-06-29 16:30:50 +00002912
Martin v. Löwis2ec36272002-10-13 10:22:08 +00002913 WIDGET-SPECIFIC OPTIONS
Raymond Hettingerff41c482003-04-06 09:01:11 +00002914
Martin v. Löwis2ec36272002-10-13 10:22:08 +00002915 autoseparators, height, maxundo,
Raymond Hettingerff41c482003-04-06 09:01:11 +00002916 spacing1, spacing2, spacing3,
Martin v. Löwis2ec36272002-10-13 10:22:08 +00002917 state, tabs, undo, width, wrap,
Raymond Hettingerff41c482003-04-06 09:01:11 +00002918
Martin v. Löwis2ec36272002-10-13 10:22:08 +00002919 """
Fredrik Lundh06d28152000-08-09 18:03:12 +00002920 Widget.__init__(self, master, 'text', cnf, kw)
Serhiy Storchaka4babb912013-11-03 14:34:25 +02002921 def bbox(self, index):
Fredrik Lundh06d28152000-08-09 18:03:12 +00002922 """Return a tuple of (x,y,width,height) which gives the bounding
Serhiy Storchaka4babb912013-11-03 14:34:25 +02002923 box of the visible part of the character at the given index."""
Fredrik Lundh06d28152000-08-09 18:03:12 +00002924 return self._getints(
Serhiy Storchaka4babb912013-11-03 14:34:25 +02002925 self.tk.call(self._w, 'bbox', index)) or None
Fredrik Lundh06d28152000-08-09 18:03:12 +00002926 def tk_textSelectTo(self, index):
2927 self.tk.call('tk_textSelectTo', self._w, index)
2928 def tk_textBackspace(self):
2929 self.tk.call('tk_textBackspace', self._w)
2930 def tk_textIndexCloser(self, a, b, c):
2931 self.tk.call('tk_textIndexCloser', self._w, a, b, c)
2932 def tk_textResetAnchor(self, index):
2933 self.tk.call('tk_textResetAnchor', self._w, index)
2934 def compare(self, index1, op, index2):
2935 """Return whether between index INDEX1 and index INDEX2 the
2936 relation OP is satisfied. OP is one of <, <=, ==, >=, >, or !=."""
2937 return self.tk.getboolean(self.tk.call(
2938 self._w, 'compare', index1, op, index2))
Martin v. Löwis5c3c4242012-03-13 13:40:42 -07002939 def count(self, index1, index2, *args): # new in Tk 8.5
2940 """Counts the number of relevant things between the two indices.
2941 If index1 is after index2, the result will be a negative number
2942 (and this holds for each of the possible options).
2943
2944 The actual items which are counted depends on the options given by
2945 args. The result is a list of integers, one for the result of each
2946 counting option given. Valid counting options are "chars",
2947 "displaychars", "displayindices", "displaylines", "indices",
2948 "lines", "xpixels" and "ypixels". There is an additional possible
2949 option "update", which if given then all subsequent options ensure
2950 that any possible out of date information is recalculated."""
2951 args = ['-%s' % arg for arg in args if not arg.startswith('-')]
2952 args += [index1, index2]
2953 res = self.tk.call(self._w, 'count', *args) or None
2954 if res is not None and len(args) <= 3:
2955 return (res, )
2956 else:
2957 return res
Fredrik Lundh06d28152000-08-09 18:03:12 +00002958 def debug(self, boolean=None):
2959 """Turn on the internal consistency checks of the B-Tree inside the text
2960 widget according to BOOLEAN."""
Serhiy Storchaka0b9e8152013-11-03 14:29:35 +02002961 if boolean is None:
2962 return self.tk.call(self._w, 'debug')
2963 self.tk.call(self._w, 'debug', boolean)
Fredrik Lundh06d28152000-08-09 18:03:12 +00002964 def delete(self, index1, index2=None):
2965 """Delete the characters between INDEX1 and INDEX2 (not included)."""
2966 self.tk.call(self._w, 'delete', index1, index2)
2967 def dlineinfo(self, index):
2968 """Return tuple (x,y,width,height,baseline) giving the bounding box
2969 and baseline position of the visible part of the line containing
2970 the character at INDEX."""
2971 return self._getints(self.tk.call(self._w, 'dlineinfo', index))
Guido van Rossum256705b2002-04-23 13:29:43 +00002972 def dump(self, index1, index2=None, command=None, **kw):
2973 """Return the contents of the widget between index1 and index2.
Raymond Hettingerff41c482003-04-06 09:01:11 +00002974
Guido van Rossum256705b2002-04-23 13:29:43 +00002975 The type of contents returned in filtered based on the keyword
2976 parameters; if 'all', 'image', 'mark', 'tag', 'text', or 'window' are
2977 given and true, then the corresponding items are returned. The result
2978 is a list of triples of the form (key, value, index). If none of the
2979 keywords are true then 'all' is used by default.
Raymond Hettingerff41c482003-04-06 09:01:11 +00002980
Guido van Rossum256705b2002-04-23 13:29:43 +00002981 If the 'command' argument is given, it is called once for each element
2982 of the list of triples, with the values of each triple serving as the
2983 arguments to the function. In this case the list is not returned."""
2984 args = []
2985 func_name = None
2986 result = None
2987 if not command:
2988 # Never call the dump command without the -command flag, since the
2989 # output could involve Tcl quoting and would be a pain to parse
2990 # right. Instead just set the command to build a list of triples
2991 # as if we had done the parsing.
2992 result = []
2993 def append_triple(key, value, index, result=result):
2994 result.append((key, value, index))
2995 command = append_triple
2996 try:
2997 if not isinstance(command, str):
2998 func_name = command = self._register(command)
2999 args += ["-command", command]
3000 for key in kw:
3001 if kw[key]: args.append("-" + key)
3002 args.append(index1)
3003 if index2:
3004 args.append(index2)
3005 self.tk.call(self._w, "dump", *args)
3006 return result
3007 finally:
3008 if func_name:
3009 self.deletecommand(func_name)
Raymond Hettingerff41c482003-04-06 09:01:11 +00003010
Martin v. Löwis2ec36272002-10-13 10:22:08 +00003011 ## new in tk8.4
3012 def edit(self, *args):
3013 """Internal method
Raymond Hettingerff41c482003-04-06 09:01:11 +00003014
3015 This method controls the undo mechanism and
3016 the modified flag. The exact behavior of the
3017 command depends on the option argument that
3018 follows the edit argument. The following forms
Martin v. Löwis2ec36272002-10-13 10:22:08 +00003019 of the command are currently supported:
Raymond Hettingerff41c482003-04-06 09:01:11 +00003020
Martin v. Löwis2ec36272002-10-13 10:22:08 +00003021 edit_modified, edit_redo, edit_reset, edit_separator
3022 and edit_undo
Raymond Hettingerff41c482003-04-06 09:01:11 +00003023
Martin v. Löwis2ec36272002-10-13 10:22:08 +00003024 """
Georg Brandlb533e262008-05-25 18:19:30 +00003025 return self.tk.call(self._w, 'edit', *args)
Martin v. Löwis2ec36272002-10-13 10:22:08 +00003026
3027 def edit_modified(self, arg=None):
3028 """Get or Set the modified flag
Raymond Hettingerff41c482003-04-06 09:01:11 +00003029
Martin v. Löwis2ec36272002-10-13 10:22:08 +00003030 If arg is not specified, returns the modified
Raymond Hettingerff41c482003-04-06 09:01:11 +00003031 flag of the widget. The insert, delete, edit undo and
3032 edit redo commands or the user can set or clear the
3033 modified flag. If boolean is specified, sets the
Martin v. Löwis2ec36272002-10-13 10:22:08 +00003034 modified flag of the widget to arg.
3035 """
3036 return self.edit("modified", arg)
Raymond Hettingerff41c482003-04-06 09:01:11 +00003037
Martin v. Löwis2ec36272002-10-13 10:22:08 +00003038 def edit_redo(self):
3039 """Redo the last undone edit
Raymond Hettingerff41c482003-04-06 09:01:11 +00003040
3041 When the undo option is true, reapplies the last
3042 undone edits provided no other edits were done since
Martin v. Löwis2ec36272002-10-13 10:22:08 +00003043 then. Generates an error when the redo stack is empty.
3044 Does nothing when the undo option is false.
3045 """
3046 return self.edit("redo")
Raymond Hettingerff41c482003-04-06 09:01:11 +00003047
Martin v. Löwis2ec36272002-10-13 10:22:08 +00003048 def edit_reset(self):
3049 """Clears the undo and redo stacks
3050 """
3051 return self.edit("reset")
Raymond Hettingerff41c482003-04-06 09:01:11 +00003052
Martin v. Löwis2ec36272002-10-13 10:22:08 +00003053 def edit_separator(self):
Raymond Hettingerff41c482003-04-06 09:01:11 +00003054 """Inserts a separator (boundary) on the undo stack.
3055
Martin v. Löwis2ec36272002-10-13 10:22:08 +00003056 Does nothing when the undo option is false
3057 """
3058 return self.edit("separator")
Raymond Hettingerff41c482003-04-06 09:01:11 +00003059
Martin v. Löwis2ec36272002-10-13 10:22:08 +00003060 def edit_undo(self):
Raymond Hettingerff41c482003-04-06 09:01:11 +00003061 """Undoes the last edit action
3062
3063 If the undo option is true. An edit action is defined
3064 as all the insert and delete commands that are recorded
3065 on the undo stack in between two separators. Generates
3066 an error when the undo stack is empty. Does nothing
Martin v. Löwis2ec36272002-10-13 10:22:08 +00003067 when the undo option is false
3068 """
3069 return self.edit("undo")
Raymond Hettingerff41c482003-04-06 09:01:11 +00003070
Fredrik Lundh06d28152000-08-09 18:03:12 +00003071 def get(self, index1, index2=None):
3072 """Return the text from INDEX1 to INDEX2 (not included)."""
3073 return self.tk.call(self._w, 'get', index1, index2)
3074 # (Image commands are new in 8.0)
3075 def image_cget(self, index, option):
3076 """Return the value of OPTION of an embedded image at INDEX."""
3077 if option[:1] != "-":
3078 option = "-" + option
3079 if option[-1:] == "_":
3080 option = option[:-1]
3081 return self.tk.call(self._w, "image", "cget", index, option)
Martin v. Löwis6ce13152002-10-10 14:36:13 +00003082 def image_configure(self, index, cnf=None, **kw):
Fredrik Lundh06d28152000-08-09 18:03:12 +00003083 """Configure an embedded image at INDEX."""
Martin v. Löwis6ce13152002-10-10 14:36:13 +00003084 return self._configure(('image', 'configure', index), cnf, kw)
Fredrik Lundh06d28152000-08-09 18:03:12 +00003085 def image_create(self, index, cnf={}, **kw):
3086 """Create an embedded image at INDEX."""
Raymond Hettingerff41c482003-04-06 09:01:11 +00003087 return self.tk.call(
3088 self._w, "image", "create", index,
3089 *self._options(cnf, kw))
Fredrik Lundh06d28152000-08-09 18:03:12 +00003090 def image_names(self):
3091 """Return all names of embedded images in this widget."""
3092 return self.tk.call(self._w, "image", "names")
3093 def index(self, index):
3094 """Return the index in the form line.char for INDEX."""
Christian Heimes57dddfb2008-01-02 18:30:52 +00003095 return str(self.tk.call(self._w, 'index', index))
Fredrik Lundh06d28152000-08-09 18:03:12 +00003096 def insert(self, index, chars, *args):
3097 """Insert CHARS before the characters at INDEX. An additional
3098 tag can be given in ARGS. Additional CHARS and tags can follow in ARGS."""
3099 self.tk.call((self._w, 'insert', index, chars) + args)
3100 def mark_gravity(self, markName, direction=None):
3101 """Change the gravity of a mark MARKNAME to DIRECTION (LEFT or RIGHT).
3102 Return the current value if None is given for DIRECTION."""
3103 return self.tk.call(
3104 (self._w, 'mark', 'gravity', markName, direction))
3105 def mark_names(self):
3106 """Return all mark names."""
3107 return self.tk.splitlist(self.tk.call(
3108 self._w, 'mark', 'names'))
3109 def mark_set(self, markName, index):
3110 """Set mark MARKNAME before the character at INDEX."""
3111 self.tk.call(self._w, 'mark', 'set', markName, index)
3112 def mark_unset(self, *markNames):
3113 """Delete all marks in MARKNAMES."""
3114 self.tk.call((self._w, 'mark', 'unset') + markNames)
3115 def mark_next(self, index):
3116 """Return the name of the next mark after INDEX."""
3117 return self.tk.call(self._w, 'mark', 'next', index) or None
3118 def mark_previous(self, index):
3119 """Return the name of the previous mark before INDEX."""
3120 return self.tk.call(self._w, 'mark', 'previous', index) or None
Martin v. Löwis5c3c4242012-03-13 13:40:42 -07003121 def peer_create(self, newPathName, cnf={}, **kw): # new in Tk 8.5
3122 """Creates a peer text widget with the given newPathName, and any
3123 optional standard configuration options. By default the peer will
Terry Jan Reedy0f847642013-03-11 18:34:00 -04003124 have the same start and end line as the parent widget, but
Martin v. Löwis5c3c4242012-03-13 13:40:42 -07003125 these can be overriden with the standard configuration options."""
3126 self.tk.call(self._w, 'peer', 'create', newPathName,
3127 *self._options(cnf, kw))
3128 def peer_names(self): # new in Tk 8.5
3129 """Returns a list of peers of this widget (this does not include
3130 the widget itself)."""
3131 return self.tk.splitlist(self.tk.call(self._w, 'peer', 'names'))
3132 def replace(self, index1, index2, chars, *args): # new in Tk 8.5
3133 """Replaces the range of characters between index1 and index2 with
3134 the given characters and tags specified by args.
3135
3136 See the method insert for some more information about args, and the
3137 method delete for information about the indices."""
3138 self.tk.call(self._w, 'replace', index1, index2, chars, *args)
Fredrik Lundh06d28152000-08-09 18:03:12 +00003139 def scan_mark(self, x, y):
3140 """Remember the current X, Y coordinates."""
3141 self.tk.call(self._w, 'scan', 'mark', x, y)
3142 def scan_dragto(self, x, y):
3143 """Adjust the view of the text to 10 times the
3144 difference between X and Y and the coordinates given in
3145 scan_mark."""
3146 self.tk.call(self._w, 'scan', 'dragto', x, y)
3147 def search(self, pattern, index, stopindex=None,
3148 forwards=None, backwards=None, exact=None,
Thomas Wouters89f507f2006-12-13 04:49:30 +00003149 regexp=None, nocase=None, count=None, elide=None):
Fredrik Lundh06d28152000-08-09 18:03:12 +00003150 """Search PATTERN beginning from INDEX until STOPINDEX.
Guilherme Poloae098992009-02-09 16:44:24 +00003151 Return the index of the first character of a match or an
3152 empty string."""
Fredrik Lundh06d28152000-08-09 18:03:12 +00003153 args = [self._w, 'search']
3154 if forwards: args.append('-forwards')
3155 if backwards: args.append('-backwards')
3156 if exact: args.append('-exact')
3157 if regexp: args.append('-regexp')
3158 if nocase: args.append('-nocase')
Thomas Wouters89f507f2006-12-13 04:49:30 +00003159 if elide: args.append('-elide')
Fredrik Lundh06d28152000-08-09 18:03:12 +00003160 if count: args.append('-count'); args.append(count)
Guilherme Poloae098992009-02-09 16:44:24 +00003161 if pattern and pattern[0] == '-': args.append('--')
Fredrik Lundh06d28152000-08-09 18:03:12 +00003162 args.append(pattern)
3163 args.append(index)
3164 if stopindex: args.append(stopindex)
Guilherme Polo56f5be52009-03-07 01:54:57 +00003165 return str(self.tk.call(tuple(args)))
Fredrik Lundh06d28152000-08-09 18:03:12 +00003166 def see(self, index):
3167 """Scroll such that the character at INDEX is visible."""
3168 self.tk.call(self._w, 'see', index)
3169 def tag_add(self, tagName, index1, *args):
3170 """Add tag TAGNAME to all characters between INDEX1 and index2 in ARGS.
3171 Additional pairs of indices may follow in ARGS."""
3172 self.tk.call(
3173 (self._w, 'tag', 'add', tagName, index1) + args)
3174 def tag_unbind(self, tagName, sequence, funcid=None):
3175 """Unbind for all characters with TAGNAME for event SEQUENCE the
3176 function identified with FUNCID."""
3177 self.tk.call(self._w, 'tag', 'bind', tagName, sequence, '')
3178 if funcid:
3179 self.deletecommand(funcid)
3180 def tag_bind(self, tagName, sequence, func, add=None):
3181 """Bind to all characters with TAGNAME at event SEQUENCE a call to function FUNC.
Guido van Rossum5917ecb2000-06-29 16:30:50 +00003182
Fredrik Lundh06d28152000-08-09 18:03:12 +00003183 An additional boolean parameter ADD specifies whether FUNC will be
3184 called additionally to the other bound function or whether it will
3185 replace the previous function. See bind for the return value."""
3186 return self._bind((self._w, 'tag', 'bind', tagName),
3187 sequence, func, add)
3188 def tag_cget(self, tagName, option):
3189 """Return the value of OPTION for tag TAGNAME."""
3190 if option[:1] != '-':
3191 option = '-' + option
3192 if option[-1:] == '_':
3193 option = option[:-1]
3194 return self.tk.call(self._w, 'tag', 'cget', tagName, option)
Martin v. Löwis6ce13152002-10-10 14:36:13 +00003195 def tag_configure(self, tagName, cnf=None, **kw):
Fredrik Lundh06d28152000-08-09 18:03:12 +00003196 """Configure a tag TAGNAME."""
Martin v. Löwis6ce13152002-10-10 14:36:13 +00003197 return self._configure(('tag', 'configure', tagName), cnf, kw)
Fredrik Lundh06d28152000-08-09 18:03:12 +00003198 tag_config = tag_configure
3199 def tag_delete(self, *tagNames):
3200 """Delete all tags in TAGNAMES."""
3201 self.tk.call((self._w, 'tag', 'delete') + tagNames)
3202 def tag_lower(self, tagName, belowThis=None):
3203 """Change the priority of tag TAGNAME such that it is lower
3204 than the priority of BELOWTHIS."""
3205 self.tk.call(self._w, 'tag', 'lower', tagName, belowThis)
3206 def tag_names(self, index=None):
3207 """Return a list of all tag names."""
3208 return self.tk.splitlist(
3209 self.tk.call(self._w, 'tag', 'names', index))
3210 def tag_nextrange(self, tagName, index1, index2=None):
3211 """Return a list of start and end index for the first sequence of
3212 characters between INDEX1 and INDEX2 which all have tag TAGNAME.
3213 The text is searched forward from INDEX1."""
3214 return self.tk.splitlist(self.tk.call(
3215 self._w, 'tag', 'nextrange', tagName, index1, index2))
3216 def tag_prevrange(self, tagName, index1, index2=None):
3217 """Return a list of start and end index for the first sequence of
3218 characters between INDEX1 and INDEX2 which all have tag TAGNAME.
3219 The text is searched backwards from INDEX1."""
3220 return self.tk.splitlist(self.tk.call(
3221 self._w, 'tag', 'prevrange', tagName, index1, index2))
3222 def tag_raise(self, tagName, aboveThis=None):
3223 """Change the priority of tag TAGNAME such that it is higher
3224 than the priority of ABOVETHIS."""
3225 self.tk.call(
3226 self._w, 'tag', 'raise', tagName, aboveThis)
3227 def tag_ranges(self, tagName):
3228 """Return a list of ranges of text which have tag TAGNAME."""
3229 return self.tk.splitlist(self.tk.call(
3230 self._w, 'tag', 'ranges', tagName))
3231 def tag_remove(self, tagName, index1, index2=None):
3232 """Remove tag TAGNAME from all characters between INDEX1 and INDEX2."""
3233 self.tk.call(
3234 self._w, 'tag', 'remove', tagName, index1, index2)
3235 def window_cget(self, index, option):
3236 """Return the value of OPTION of an embedded window at INDEX."""
3237 if option[:1] != '-':
3238 option = '-' + option
3239 if option[-1:] == '_':
3240 option = option[:-1]
3241 return self.tk.call(self._w, 'window', 'cget', index, option)
Martin v. Löwis6ce13152002-10-10 14:36:13 +00003242 def window_configure(self, index, cnf=None, **kw):
Fredrik Lundh06d28152000-08-09 18:03:12 +00003243 """Configure an embedded window at INDEX."""
Martin v. Löwis6ce13152002-10-10 14:36:13 +00003244 return self._configure(('window', 'configure', index), cnf, kw)
Fredrik Lundh06d28152000-08-09 18:03:12 +00003245 window_config = window_configure
3246 def window_create(self, index, cnf={}, **kw):
3247 """Create a window at INDEX."""
3248 self.tk.call(
3249 (self._w, 'window', 'create', index)
3250 + self._options(cnf, kw))
3251 def window_names(self):
3252 """Return all names of embedded windows in this widget."""
3253 return self.tk.splitlist(
3254 self.tk.call(self._w, 'window', 'names'))
Fredrik Lundh06d28152000-08-09 18:03:12 +00003255 def yview_pickplace(self, *what):
3256 """Obsolete function, use see."""
3257 self.tk.call((self._w, 'yview', '-pickplace') + what)
Guido van Rossum18468821994-06-20 07:49:28 +00003258
Martin v. Löwis2ec36272002-10-13 10:22:08 +00003259
Guido van Rossum28574b51996-10-21 15:16:51 +00003260class _setit:
Fredrik Lundh06d28152000-08-09 18:03:12 +00003261 """Internal class. It wraps the command in the widget OptionMenu."""
3262 def __init__(self, var, value, callback=None):
3263 self.__value = value
3264 self.__var = var
3265 self.__callback = callback
3266 def __call__(self, *args):
3267 self.__var.set(self.__value)
3268 if self.__callback:
Raymond Hettingerff41c482003-04-06 09:01:11 +00003269 self.__callback(self.__value, *args)
Guido van Rossum28574b51996-10-21 15:16:51 +00003270
3271class OptionMenu(Menubutton):
Fredrik Lundh06d28152000-08-09 18:03:12 +00003272 """OptionMenu which allows the user to select a value from a menu."""
3273 def __init__(self, master, variable, value, *values, **kwargs):
3274 """Construct an optionmenu widget with the parent MASTER, with
3275 the resource textvariable set to VARIABLE, the initially selected
3276 value VALUE, the other menu values VALUES and an additional
3277 keyword argument command."""
3278 kw = {"borderwidth": 2, "textvariable": variable,
3279 "indicatoron": 1, "relief": RAISED, "anchor": "c",
3280 "highlightthickness": 2}
3281 Widget.__init__(self, master, "menubutton", kw)
3282 self.widgetName = 'tk_optionMenu'
3283 menu = self.__menu = Menu(self, name="menu", tearoff=0)
3284 self.menuname = menu._w
3285 # 'command' is the only supported keyword
3286 callback = kwargs.get('command')
Guido van Rossume014a132006-08-19 16:53:45 +00003287 if 'command' in kwargs:
Fredrik Lundh06d28152000-08-09 18:03:12 +00003288 del kwargs['command']
3289 if kwargs:
Collin Winterce36ad82007-08-30 01:19:48 +00003290 raise TclError('unknown option -'+kwargs.keys()[0])
Fredrik Lundh06d28152000-08-09 18:03:12 +00003291 menu.add_command(label=value,
3292 command=_setit(variable, value, callback))
3293 for v in values:
3294 menu.add_command(label=v,
3295 command=_setit(variable, v, callback))
3296 self["menu"] = menu
Guido van Rossum28574b51996-10-21 15:16:51 +00003297
Fredrik Lundh06d28152000-08-09 18:03:12 +00003298 def __getitem__(self, name):
3299 if name == 'menu':
3300 return self.__menu
3301 return Widget.__getitem__(self, name)
Guido van Rossum28574b51996-10-21 15:16:51 +00003302
Fredrik Lundh06d28152000-08-09 18:03:12 +00003303 def destroy(self):
3304 """Destroy this widget and the associated menu."""
3305 Menubutton.destroy(self)
3306 self.__menu = None
Guido van Rossumbf4d8f91995-09-01 20:35:37 +00003307
Guido van Rossum35f67fb1995-08-04 03:50:29 +00003308class Image:
Fredrik Lundh06d28152000-08-09 18:03:12 +00003309 """Base class for images."""
Martin v. Löwis0d8ce612000-09-08 16:28:30 +00003310 _last_id = 0
Fredrik Lundh06d28152000-08-09 18:03:12 +00003311 def __init__(self, imgtype, name=None, cnf={}, master=None, **kw):
3312 self.name = None
3313 if not master:
3314 master = _default_root
3315 if not master:
Collin Winterce36ad82007-08-30 01:19:48 +00003316 raise RuntimeError('Too early to create image')
Fredrik Lundh06d28152000-08-09 18:03:12 +00003317 self.tk = master.tk
3318 if not name:
Martin v. Löwis0d8ce612000-09-08 16:28:30 +00003319 Image._last_id += 1
Walter Dörwald70a6b492004-02-12 17:35:32 +00003320 name = "pyimage%r" % (Image._last_id,) # tk itself would use image<x>
Fredrik Lundh06d28152000-08-09 18:03:12 +00003321 # The following is needed for systems where id(x)
3322 # can return a negative number, such as Linux/m68k:
3323 if name[0] == '-': name = '_' + name[1:]
3324 if kw and cnf: cnf = _cnfmerge((cnf, kw))
3325 elif kw: cnf = kw
3326 options = ()
3327 for k, v in cnf.items():
Florent Xicluna5d1155c2011-10-28 14:45:05 +02003328 if callable(v):
Fredrik Lundh06d28152000-08-09 18:03:12 +00003329 v = self._register(v)
3330 options = options + ('-'+k, v)
3331 self.tk.call(('image', 'create', imgtype, name,) + options)
3332 self.name = name
3333 def __str__(self): return self.name
3334 def __del__(self):
3335 if self.name:
3336 try:
3337 self.tk.call('image', 'delete', self.name)
3338 except TclError:
3339 # May happen if the root was destroyed
3340 pass
3341 def __setitem__(self, key, value):
3342 self.tk.call(self.name, 'configure', '-'+key, value)
3343 def __getitem__(self, key):
3344 return self.tk.call(self.name, 'configure', '-'+key)
3345 def configure(self, **kw):
3346 """Configure the image."""
3347 res = ()
3348 for k, v in _cnfmerge(kw).items():
3349 if v is not None:
3350 if k[-1] == '_': k = k[:-1]
Florent Xicluna5d1155c2011-10-28 14:45:05 +02003351 if callable(v):
Fredrik Lundh06d28152000-08-09 18:03:12 +00003352 v = self._register(v)
3353 res = res + ('-'+k, v)
3354 self.tk.call((self.name, 'config') + res)
3355 config = configure
3356 def height(self):
3357 """Return the height of the image."""
3358 return getint(
3359 self.tk.call('image', 'height', self.name))
3360 def type(self):
3361 """Return the type of the imgage, e.g. "photo" or "bitmap"."""
3362 return self.tk.call('image', 'type', self.name)
3363 def width(self):
3364 """Return the width of the image."""
3365 return getint(
3366 self.tk.call('image', 'width', self.name))
Guido van Rossum35f67fb1995-08-04 03:50:29 +00003367
3368class PhotoImage(Image):
Fredrik Lundh06d28152000-08-09 18:03:12 +00003369 """Widget which can display colored images in GIF, PPM/PGM format."""
3370 def __init__(self, name=None, cnf={}, master=None, **kw):
3371 """Create an image with NAME.
Guido van Rossum5917ecb2000-06-29 16:30:50 +00003372
Fredrik Lundh06d28152000-08-09 18:03:12 +00003373 Valid resource names: data, format, file, gamma, height, palette,
3374 width."""
Raymond Hettingerff41c482003-04-06 09:01:11 +00003375 Image.__init__(self, 'photo', name, cnf, master, **kw)
Fredrik Lundh06d28152000-08-09 18:03:12 +00003376 def blank(self):
3377 """Display a transparent image."""
3378 self.tk.call(self.name, 'blank')
3379 def cget(self, option):
3380 """Return the value of OPTION."""
3381 return self.tk.call(self.name, 'cget', '-' + option)
3382 # XXX config
3383 def __getitem__(self, key):
3384 return self.tk.call(self.name, 'cget', '-' + key)
3385 # XXX copy -from, -to, ...?
3386 def copy(self):
3387 """Return a new PhotoImage with the same image as this widget."""
3388 destImage = PhotoImage()
3389 self.tk.call(destImage, 'copy', self.name)
3390 return destImage
3391 def zoom(self,x,y=''):
3392 """Return a new PhotoImage with the same image as this widget
3393 but zoom it with X and Y."""
3394 destImage = PhotoImage()
3395 if y=='': y=x
3396 self.tk.call(destImage, 'copy', self.name, '-zoom',x,y)
3397 return destImage
3398 def subsample(self,x,y=''):
3399 """Return a new PhotoImage based on the same image as this widget
3400 but use only every Xth or Yth pixel."""
3401 destImage = PhotoImage()
3402 if y=='': y=x
3403 self.tk.call(destImage, 'copy', self.name, '-subsample',x,y)
3404 return destImage
3405 def get(self, x, y):
3406 """Return the color (red, green, blue) of the pixel at X,Y."""
3407 return self.tk.call(self.name, 'get', x, y)
3408 def put(self, data, to=None):
Mark Dickinson934896d2009-02-21 20:59:32 +00003409 """Put row formatted colors to image starting from
Fredrik Lundh06d28152000-08-09 18:03:12 +00003410 position TO, e.g. image.put("{red green} {blue yellow}", to=(4,6))"""
3411 args = (self.name, 'put', data)
3412 if to:
3413 if to[0] == '-to':
3414 to = to[1:]
3415 args = args + ('-to',) + tuple(to)
3416 self.tk.call(args)
3417 # XXX read
3418 def write(self, filename, format=None, from_coords=None):
3419 """Write image to file FILENAME in FORMAT starting from
3420 position FROM_COORDS."""
3421 args = (self.name, 'write', filename)
3422 if format:
3423 args = args + ('-format', format)
3424 if from_coords:
3425 args = args + ('-from',) + tuple(from_coords)
3426 self.tk.call(args)
Guido van Rossum35f67fb1995-08-04 03:50:29 +00003427
3428class BitmapImage(Image):
Fredrik Lundh06d28152000-08-09 18:03:12 +00003429 """Widget which can display a bitmap."""
3430 def __init__(self, name=None, cnf={}, master=None, **kw):
3431 """Create a bitmap with NAME.
Guido van Rossum5917ecb2000-06-29 16:30:50 +00003432
Fredrik Lundh06d28152000-08-09 18:03:12 +00003433 Valid resource names: background, data, file, foreground, maskdata, maskfile."""
Raymond Hettingerff41c482003-04-06 09:01:11 +00003434 Image.__init__(self, 'bitmap', name, cnf, master, **kw)
Guido van Rossum35f67fb1995-08-04 03:50:29 +00003435
3436def image_names(): return _default_root.tk.call('image', 'names')
3437def image_types(): return _default_root.tk.call('image', 'types')
3438
Martin v. Löwis2ec36272002-10-13 10:22:08 +00003439
Guilherme Polo1fff0082009-08-14 15:05:30 +00003440class Spinbox(Widget, XView):
Martin v. Löwis2ec36272002-10-13 10:22:08 +00003441 """spinbox widget."""
3442 def __init__(self, master=None, cnf={}, **kw):
3443 """Construct a spinbox widget with the parent MASTER.
Raymond Hettingerff41c482003-04-06 09:01:11 +00003444
Martin v. Löwis2ec36272002-10-13 10:22:08 +00003445 STANDARD OPTIONS
Raymond Hettingerff41c482003-04-06 09:01:11 +00003446
Martin v. Löwis2ec36272002-10-13 10:22:08 +00003447 activebackground, background, borderwidth,
3448 cursor, exportselection, font, foreground,
3449 highlightbackground, highlightcolor,
3450 highlightthickness, insertbackground,
3451 insertborderwidth, insertofftime,
Raymond Hettingerff41c482003-04-06 09:01:11 +00003452 insertontime, insertwidth, justify, relief,
3453 repeatdelay, repeatinterval,
Martin v. Löwis2ec36272002-10-13 10:22:08 +00003454 selectbackground, selectborderwidth
3455 selectforeground, takefocus, textvariable
3456 xscrollcommand.
Raymond Hettingerff41c482003-04-06 09:01:11 +00003457
Martin v. Löwis2ec36272002-10-13 10:22:08 +00003458 WIDGET-SPECIFIC OPTIONS
Raymond Hettingerff41c482003-04-06 09:01:11 +00003459
3460 buttonbackground, buttoncursor,
3461 buttondownrelief, buttonuprelief,
3462 command, disabledbackground,
3463 disabledforeground, format, from,
3464 invalidcommand, increment,
3465 readonlybackground, state, to,
Martin v. Löwis2ec36272002-10-13 10:22:08 +00003466 validate, validatecommand values,
3467 width, wrap,
3468 """
3469 Widget.__init__(self, master, 'spinbox', cnf, kw)
Raymond Hettingerff41c482003-04-06 09:01:11 +00003470
Martin v. Löwis2ec36272002-10-13 10:22:08 +00003471 def bbox(self, index):
Raymond Hettingerff41c482003-04-06 09:01:11 +00003472 """Return a tuple of X1,Y1,X2,Y2 coordinates for a
3473 rectangle which encloses the character given by index.
3474
3475 The first two elements of the list give the x and y
3476 coordinates of the upper-left corner of the screen
3477 area covered by the character (in pixels relative
3478 to the widget) and the last two elements give the
3479 width and height of the character, in pixels. The
3480 bounding box may refer to a region outside the
Martin v. Löwis2ec36272002-10-13 10:22:08 +00003481 visible area of the window.
3482 """
Serhiy Storchaka2849e0d2013-11-03 14:13:34 +02003483 return self._getints(self.tk.call(self._w, 'bbox', index)) or None
Raymond Hettingerff41c482003-04-06 09:01:11 +00003484
Martin v. Löwis2ec36272002-10-13 10:22:08 +00003485 def delete(self, first, last=None):
3486 """Delete one or more elements of the spinbox.
Raymond Hettingerff41c482003-04-06 09:01:11 +00003487
3488 First is the index of the first character to delete,
3489 and last is the index of the character just after
3490 the last one to delete. If last isn't specified it
3491 defaults to first+1, i.e. a single character is
Martin v. Löwis2ec36272002-10-13 10:22:08 +00003492 deleted. This command returns an empty string.
3493 """
3494 return self.tk.call(self._w, 'delete', first, last)
Raymond Hettingerff41c482003-04-06 09:01:11 +00003495
Martin v. Löwis2ec36272002-10-13 10:22:08 +00003496 def get(self):
3497 """Returns the spinbox's string"""
3498 return self.tk.call(self._w, 'get')
Raymond Hettingerff41c482003-04-06 09:01:11 +00003499
Martin v. Löwis2ec36272002-10-13 10:22:08 +00003500 def icursor(self, index):
3501 """Alter the position of the insertion cursor.
Raymond Hettingerff41c482003-04-06 09:01:11 +00003502
3503 The insertion cursor will be displayed just before
Martin v. Löwis2ec36272002-10-13 10:22:08 +00003504 the character given by index. Returns an empty string
3505 """
3506 return self.tk.call(self._w, 'icursor', index)
Raymond Hettingerff41c482003-04-06 09:01:11 +00003507
Martin v. Löwis2ec36272002-10-13 10:22:08 +00003508 def identify(self, x, y):
Raymond Hettingerff41c482003-04-06 09:01:11 +00003509 """Returns the name of the widget at position x, y
3510
Martin v. Löwis2ec36272002-10-13 10:22:08 +00003511 Return value is one of: none, buttondown, buttonup, entry
3512 """
3513 return self.tk.call(self._w, 'identify', x, y)
Raymond Hettingerff41c482003-04-06 09:01:11 +00003514
Martin v. Löwis2ec36272002-10-13 10:22:08 +00003515 def index(self, index):
3516 """Returns the numerical index corresponding to index
3517 """
3518 return self.tk.call(self._w, 'index', index)
Raymond Hettingerff41c482003-04-06 09:01:11 +00003519
Martin v. Löwis2ec36272002-10-13 10:22:08 +00003520 def insert(self, index, s):
Raymond Hettingerff41c482003-04-06 09:01:11 +00003521 """Insert string s at index
3522
Martin v. Löwis2ec36272002-10-13 10:22:08 +00003523 Returns an empty string.
3524 """
3525 return self.tk.call(self._w, 'insert', index, s)
Raymond Hettingerff41c482003-04-06 09:01:11 +00003526
Martin v. Löwis2ec36272002-10-13 10:22:08 +00003527 def invoke(self, element):
3528 """Causes the specified element to be invoked
Raymond Hettingerff41c482003-04-06 09:01:11 +00003529
Martin v. Löwis2ec36272002-10-13 10:22:08 +00003530 The element could be buttondown or buttonup
3531 triggering the action associated with it.
3532 """
3533 return self.tk.call(self._w, 'invoke', element)
Raymond Hettingerff41c482003-04-06 09:01:11 +00003534
Martin v. Löwis2ec36272002-10-13 10:22:08 +00003535 def scan(self, *args):
3536 """Internal function."""
3537 return self._getints(
3538 self.tk.call((self._w, 'scan') + args)) or ()
Raymond Hettingerff41c482003-04-06 09:01:11 +00003539
Martin v. Löwis2ec36272002-10-13 10:22:08 +00003540 def scan_mark(self, x):
Raymond Hettingerff41c482003-04-06 09:01:11 +00003541 """Records x and the current view in the spinbox window;
3542
3543 used in conjunction with later scan dragto commands.
3544 Typically this command is associated with a mouse button
Martin v. Löwis2ec36272002-10-13 10:22:08 +00003545 press in the widget. It returns an empty string.
3546 """
3547 return self.scan("mark", x)
Raymond Hettingerff41c482003-04-06 09:01:11 +00003548
Martin v. Löwis2ec36272002-10-13 10:22:08 +00003549 def scan_dragto(self, x):
Raymond Hettingerff41c482003-04-06 09:01:11 +00003550 """Compute the difference between the given x argument
Martin v. Löwis2ec36272002-10-13 10:22:08 +00003551 and the x argument to the last scan mark command
Raymond Hettingerff41c482003-04-06 09:01:11 +00003552
3553 It then adjusts the view left or right by 10 times the
3554 difference in x-coordinates. This command is typically
3555 associated with mouse motion events in the widget, to
Martin v. Löwis2ec36272002-10-13 10:22:08 +00003556 produce the effect of dragging the spinbox at high speed
3557 through the window. The return value is an empty string.
3558 """
3559 return self.scan("dragto", x)
Raymond Hettingerff41c482003-04-06 09:01:11 +00003560
Martin v. Löwis2ec36272002-10-13 10:22:08 +00003561 def selection(self, *args):
3562 """Internal function."""
3563 return self._getints(
3564 self.tk.call((self._w, 'selection') + args)) or ()
Raymond Hettingerff41c482003-04-06 09:01:11 +00003565
Martin v. Löwis2ec36272002-10-13 10:22:08 +00003566 def selection_adjust(self, index):
3567 """Locate the end of the selection nearest to the character
Raymond Hettingerff41c482003-04-06 09:01:11 +00003568 given by index,
3569
3570 Then adjust that end of the selection to be at index
3571 (i.e including but not going beyond index). The other
Martin v. Löwis2ec36272002-10-13 10:22:08 +00003572 end of the selection is made the anchor point for future
Raymond Hettingerff41c482003-04-06 09:01:11 +00003573 select to commands. If the selection isn't currently in
3574 the spinbox, then a new selection is created to include
3575 the characters between index and the most recent selection
Martin v. Löwis2ec36272002-10-13 10:22:08 +00003576 anchor point, inclusive. Returns an empty string.
3577 """
3578 return self.selection("adjust", index)
Raymond Hettingerff41c482003-04-06 09:01:11 +00003579
Martin v. Löwis2ec36272002-10-13 10:22:08 +00003580 def selection_clear(self):
Raymond Hettingerff41c482003-04-06 09:01:11 +00003581 """Clear the selection
3582
3583 If the selection isn't in this widget then the
Martin v. Löwis2ec36272002-10-13 10:22:08 +00003584 command has no effect. Returns an empty string.
3585 """
3586 return self.selection("clear")
Raymond Hettingerff41c482003-04-06 09:01:11 +00003587
Martin v. Löwis2ec36272002-10-13 10:22:08 +00003588 def selection_element(self, element=None):
Raymond Hettingerff41c482003-04-06 09:01:11 +00003589 """Sets or gets the currently selected element.
3590
3591 If a spinbutton element is specified, it will be
Martin v. Löwis2ec36272002-10-13 10:22:08 +00003592 displayed depressed
3593 """
3594 return self.selection("element", element)
3595
3596###########################################################################
3597
3598class LabelFrame(Widget):
3599 """labelframe widget."""
3600 def __init__(self, master=None, cnf={}, **kw):
3601 """Construct a labelframe widget with the parent MASTER.
Raymond Hettingerff41c482003-04-06 09:01:11 +00003602
Martin v. Löwis2ec36272002-10-13 10:22:08 +00003603 STANDARD OPTIONS
Raymond Hettingerff41c482003-04-06 09:01:11 +00003604
3605 borderwidth, cursor, font, foreground,
3606 highlightbackground, highlightcolor,
3607 highlightthickness, padx, pady, relief,
Martin v. Löwis2ec36272002-10-13 10:22:08 +00003608 takefocus, text
Raymond Hettingerff41c482003-04-06 09:01:11 +00003609
Martin v. Löwis2ec36272002-10-13 10:22:08 +00003610 WIDGET-SPECIFIC OPTIONS
Raymond Hettingerff41c482003-04-06 09:01:11 +00003611
3612 background, class, colormap, container,
3613 height, labelanchor, labelwidget,
Martin v. Löwis2ec36272002-10-13 10:22:08 +00003614 visual, width
3615 """
3616 Widget.__init__(self, master, 'labelframe', cnf, kw)
Raymond Hettingerff41c482003-04-06 09:01:11 +00003617
Martin v. Löwis2ec36272002-10-13 10:22:08 +00003618########################################################################
3619
3620class PanedWindow(Widget):
3621 """panedwindow widget."""
3622 def __init__(self, master=None, cnf={}, **kw):
3623 """Construct a panedwindow widget with the parent MASTER.
Raymond Hettingerff41c482003-04-06 09:01:11 +00003624
Martin v. Löwis2ec36272002-10-13 10:22:08 +00003625 STANDARD OPTIONS
Raymond Hettingerff41c482003-04-06 09:01:11 +00003626
Martin v. Löwis2ec36272002-10-13 10:22:08 +00003627 background, borderwidth, cursor, height,
3628 orient, relief, width
Raymond Hettingerff41c482003-04-06 09:01:11 +00003629
Martin v. Löwis2ec36272002-10-13 10:22:08 +00003630 WIDGET-SPECIFIC OPTIONS
Raymond Hettingerff41c482003-04-06 09:01:11 +00003631
3632 handlepad, handlesize, opaqueresize,
3633 sashcursor, sashpad, sashrelief,
Martin v. Löwis2ec36272002-10-13 10:22:08 +00003634 sashwidth, showhandle,
3635 """
3636 Widget.__init__(self, master, 'panedwindow', cnf, kw)
3637
3638 def add(self, child, **kw):
Raymond Hettingerff41c482003-04-06 09:01:11 +00003639 """Add a child widget to the panedwindow in a new pane.
3640
3641 The child argument is the name of the child widget
3642 followed by pairs of arguments that specify how to
Guilherme Polo86425562009-05-31 21:35:23 +00003643 manage the windows. The possible options and values
3644 are the ones accepted by the paneconfigure method.
Martin v. Löwis2ec36272002-10-13 10:22:08 +00003645 """
3646 self.tk.call((self._w, 'add', child) + self._options(kw))
Raymond Hettingerff41c482003-04-06 09:01:11 +00003647
Martin v. Löwis2ec36272002-10-13 10:22:08 +00003648 def remove(self, child):
3649 """Remove the pane containing child from the panedwindow
Raymond Hettingerff41c482003-04-06 09:01:11 +00003650
Martin v. Löwis2ec36272002-10-13 10:22:08 +00003651 All geometry management options for child will be forgotten.
3652 """
3653 self.tk.call(self._w, 'forget', child)
3654 forget=remove
Raymond Hettingerff41c482003-04-06 09:01:11 +00003655
Martin v. Löwis2ec36272002-10-13 10:22:08 +00003656 def identify(self, x, y):
3657 """Identify the panedwindow component at point x, y
Raymond Hettingerff41c482003-04-06 09:01:11 +00003658
3659 If the point is over a sash or a sash handle, the result
Martin v. Löwis2ec36272002-10-13 10:22:08 +00003660 is a two element list containing the index of the sash or
Raymond Hettingerff41c482003-04-06 09:01:11 +00003661 handle, and a word indicating whether it is over a sash
3662 or a handle, such as {0 sash} or {2 handle}. If the point
3663 is over any other part of the panedwindow, the result is
Martin v. Löwis2ec36272002-10-13 10:22:08 +00003664 an empty list.
3665 """
3666 return self.tk.call(self._w, 'identify', x, y)
Raymond Hettingerff41c482003-04-06 09:01:11 +00003667
Martin v. Löwis2ec36272002-10-13 10:22:08 +00003668 def proxy(self, *args):
3669 """Internal function."""
3670 return self._getints(
Raymond Hettingerff41c482003-04-06 09:01:11 +00003671 self.tk.call((self._w, 'proxy') + args)) or ()
3672
Martin v. Löwis2ec36272002-10-13 10:22:08 +00003673 def proxy_coord(self):
3674 """Return the x and y pair of the most recent proxy location
3675 """
3676 return self.proxy("coord")
Raymond Hettingerff41c482003-04-06 09:01:11 +00003677
Martin v. Löwis2ec36272002-10-13 10:22:08 +00003678 def proxy_forget(self):
3679 """Remove the proxy from the display.
3680 """
3681 return self.proxy("forget")
Raymond Hettingerff41c482003-04-06 09:01:11 +00003682
Martin v. Löwis2ec36272002-10-13 10:22:08 +00003683 def proxy_place(self, x, y):
Raymond Hettingerff41c482003-04-06 09:01:11 +00003684 """Place the proxy at the given x and y coordinates.
Martin v. Löwis2ec36272002-10-13 10:22:08 +00003685 """
3686 return self.proxy("place", x, y)
Raymond Hettingerff41c482003-04-06 09:01:11 +00003687
Martin v. Löwis2ec36272002-10-13 10:22:08 +00003688 def sash(self, *args):
3689 """Internal function."""
3690 return self._getints(
3691 self.tk.call((self._w, 'sash') + args)) or ()
Raymond Hettingerff41c482003-04-06 09:01:11 +00003692
Martin v. Löwis2ec36272002-10-13 10:22:08 +00003693 def sash_coord(self, index):
Raymond Hettingerff41c482003-04-06 09:01:11 +00003694 """Return the current x and y pair for the sash given by index.
3695
3696 Index must be an integer between 0 and 1 less than the
3697 number of panes in the panedwindow. The coordinates given are
3698 those of the top left corner of the region containing the sash.
3699 pathName sash dragto index x y This command computes the
3700 difference between the given coordinates and the coordinates
3701 given to the last sash coord command for the given sash. It then
3702 moves that sash the computed difference. The return value is the
Martin v. Löwis2ec36272002-10-13 10:22:08 +00003703 empty string.
3704 """
3705 return self.sash("coord", index)
Raymond Hettingerff41c482003-04-06 09:01:11 +00003706
Martin v. Löwis2ec36272002-10-13 10:22:08 +00003707 def sash_mark(self, index):
Raymond Hettingerff41c482003-04-06 09:01:11 +00003708 """Records x and y for the sash given by index;
3709
Martin v. Löwis2ec36272002-10-13 10:22:08 +00003710 Used in conjunction with later dragto commands to move the sash.
3711 """
3712 return self.sash("mark", index)
Raymond Hettingerff41c482003-04-06 09:01:11 +00003713
Martin v. Löwis2ec36272002-10-13 10:22:08 +00003714 def sash_place(self, index, x, y):
3715 """Place the sash given by index at the given coordinates
3716 """
3717 return self.sash("place", index, x, y)
Raymond Hettingerff41c482003-04-06 09:01:11 +00003718
Martin v. Löwis2ec36272002-10-13 10:22:08 +00003719 def panecget(self, child, option):
Raymond Hettingerff41c482003-04-06 09:01:11 +00003720 """Query a management option for window.
3721
Martin v. Löwis2ec36272002-10-13 10:22:08 +00003722 Option may be any value allowed by the paneconfigure subcommand
3723 """
3724 return self.tk.call(
3725 (self._w, 'panecget') + (child, '-'+option))
Raymond Hettingerff41c482003-04-06 09:01:11 +00003726
Martin v. Löwis2ec36272002-10-13 10:22:08 +00003727 def paneconfigure(self, tagOrId, cnf=None, **kw):
Raymond Hettingerff41c482003-04-06 09:01:11 +00003728 """Query or modify the management options for window.
3729
Martin v. Löwis2ec36272002-10-13 10:22:08 +00003730 If no option is specified, returns a list describing all
Raymond Hettingerff41c482003-04-06 09:01:11 +00003731 of the available options for pathName. If option is
3732 specified with no value, then the command returns a list
3733 describing the one named option (this list will be identical
3734 to the corresponding sublist of the value returned if no
3735 option is specified). If one or more option-value pairs are
3736 specified, then the command modifies the given widget
3737 option(s) to have the given value(s); in this case the
3738 command returns an empty string. The following options
Martin v. Löwis2ec36272002-10-13 10:22:08 +00003739 are supported:
Raymond Hettingerff41c482003-04-06 09:01:11 +00003740
Martin v. Löwis2ec36272002-10-13 10:22:08 +00003741 after window
Raymond Hettingerff41c482003-04-06 09:01:11 +00003742 Insert the window after the window specified. window
Martin v. Löwis2ec36272002-10-13 10:22:08 +00003743 should be the name of a window already managed by pathName.
3744 before window
Raymond Hettingerff41c482003-04-06 09:01:11 +00003745 Insert the window before the window specified. window
Martin v. Löwis2ec36272002-10-13 10:22:08 +00003746 should be the name of a window already managed by pathName.
3747 height size
Raymond Hettingerff41c482003-04-06 09:01:11 +00003748 Specify a height for the window. The height will be the
3749 outer dimension of the window including its border, if
3750 any. If size is an empty string, or if -height is not
3751 specified, then the height requested internally by the
3752 window will be used initially; the height may later be
3753 adjusted by the movement of sashes in the panedwindow.
Martin v. Löwis2ec36272002-10-13 10:22:08 +00003754 Size may be any value accepted by Tk_GetPixels.
3755 minsize n
Raymond Hettingerff41c482003-04-06 09:01:11 +00003756 Specifies that the size of the window cannot be made
3757 less than n. This constraint only affects the size of
3758 the widget in the paned dimension -- the x dimension
3759 for horizontal panedwindows, the y dimension for
3760 vertical panedwindows. May be any value accepted by
Martin v. Löwis2ec36272002-10-13 10:22:08 +00003761 Tk_GetPixels.
3762 padx n
Raymond Hettingerff41c482003-04-06 09:01:11 +00003763 Specifies a non-negative value indicating how much
3764 extra space to leave on each side of the window in
3765 the X-direction. The value may have any of the forms
Martin v. Löwis2ec36272002-10-13 10:22:08 +00003766 accepted by Tk_GetPixels.
3767 pady n
3768 Specifies a non-negative value indicating how much
Raymond Hettingerff41c482003-04-06 09:01:11 +00003769 extra space to leave on each side of the window in
3770 the Y-direction. The value may have any of the forms
Martin v. Löwis2ec36272002-10-13 10:22:08 +00003771 accepted by Tk_GetPixels.
3772 sticky style
Raymond Hettingerff41c482003-04-06 09:01:11 +00003773 If a window's pane is larger than the requested
3774 dimensions of the window, this option may be used
3775 to position (or stretch) the window within its pane.
3776 Style is a string that contains zero or more of the
3777 characters n, s, e or w. The string can optionally
3778 contains spaces or commas, but they are ignored. Each
3779 letter refers to a side (north, south, east, or west)
3780 that the window will "stick" to. If both n and s
3781 (or e and w) are specified, the window will be
3782 stretched to fill the entire height (or width) of
Martin v. Löwis2ec36272002-10-13 10:22:08 +00003783 its cavity.
3784 width size
Raymond Hettingerff41c482003-04-06 09:01:11 +00003785 Specify a width for the window. The width will be
3786 the outer dimension of the window including its
3787 border, if any. If size is an empty string, or
Martin v. Löwis2ec36272002-10-13 10:22:08 +00003788 if -width is not specified, then the width requested
Raymond Hettingerff41c482003-04-06 09:01:11 +00003789 internally by the window will be used initially; the
3790 width may later be adjusted by the movement of sashes
3791 in the panedwindow. Size may be any value accepted by
Martin v. Löwis2ec36272002-10-13 10:22:08 +00003792 Tk_GetPixels.
Raymond Hettingerff41c482003-04-06 09:01:11 +00003793
Martin v. Löwis2ec36272002-10-13 10:22:08 +00003794 """
3795 if cnf is None and not kw:
Serhiy Storchaka848972c2013-12-25 16:35:38 +02003796 return self._getconfigure(self._w, 'paneconfigure', tagOrId)
Guido van Rossum13257902007-06-07 23:15:56 +00003797 if isinstance(cnf, str) and not kw:
Serhiy Storchaka848972c2013-12-25 16:35:38 +02003798 return self._getconfigure1(
3799 self._w, 'paneconfigure', tagOrId, '-'+cnf)
Martin v. Löwis2ec36272002-10-13 10:22:08 +00003800 self.tk.call((self._w, 'paneconfigure', tagOrId) +
3801 self._options(cnf, kw))
3802 paneconfig = paneconfigure
3803
3804 def panes(self):
3805 """Returns an ordered list of the child panes."""
3806 return self.tk.call(self._w, 'panes')
3807
Guido van Rossumaec5dc91994-06-27 07:55:12 +00003808######################################################################
3809# Extensions:
3810
3811class Studbutton(Button):
Fredrik Lundh06d28152000-08-09 18:03:12 +00003812 def __init__(self, master=None, cnf={}, **kw):
3813 Widget.__init__(self, master, 'studbutton', cnf, kw)
3814 self.bind('<Any-Enter>', self.tkButtonEnter)
3815 self.bind('<Any-Leave>', self.tkButtonLeave)
3816 self.bind('<1>', self.tkButtonDown)
3817 self.bind('<ButtonRelease-1>', self.tkButtonUp)
Guido van Rossumaec5dc91994-06-27 07:55:12 +00003818
3819class Tributton(Button):
Fredrik Lundh06d28152000-08-09 18:03:12 +00003820 def __init__(self, master=None, cnf={}, **kw):
3821 Widget.__init__(self, master, 'tributton', cnf, kw)
3822 self.bind('<Any-Enter>', self.tkButtonEnter)
3823 self.bind('<Any-Leave>', self.tkButtonLeave)
3824 self.bind('<1>', self.tkButtonDown)
3825 self.bind('<ButtonRelease-1>', self.tkButtonUp)
3826 self['fg'] = self['bg']
3827 self['activebackground'] = self['bg']
Guido van Rossum37dcab11996-05-16 16:00:19 +00003828
Guido van Rossumc417ef81996-08-21 23:38:59 +00003829######################################################################
3830# Test:
3831
3832def _test():
Fredrik Lundh06d28152000-08-09 18:03:12 +00003833 root = Tk()
3834 text = "This is Tcl/Tk version %s" % TclVersion
3835 if TclVersion >= 8.1:
Walter Dörwald5de48bd2007-06-11 21:38:39 +00003836 text += "\nThis should be a cedilla: \xe7"
Fredrik Lundh06d28152000-08-09 18:03:12 +00003837 label = Label(root, text=text)
3838 label.pack()
3839 test = Button(root, text="Click me!",
3840 command=lambda root=root: root.test.configure(
3841 text="[%s]" % root.test['text']))
3842 test.pack()
3843 root.test = test
3844 quit = Button(root, text="QUIT", command=root.destroy)
3845 quit.pack()
3846 # The following three commands are needed so the window pops
3847 # up on top on Windows...
3848 root.iconify()
3849 root.update()
3850 root.deiconify()
3851 root.mainloop()
Guido van Rossumc417ef81996-08-21 23:38:59 +00003852
3853if __name__ == '__main__':
Fredrik Lundh06d28152000-08-09 18:03:12 +00003854 _test()