blob: da430dfd77ebc7618e2b528dce61a733cce4302c [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
Andrew Svetlova966c6f2012-03-21 23:52:59 +020034
Guido van Rossumf8d579c1999-01-04 18:06:45 +000035import _tkinter # If this fails your Python may not be configured for Tk
Guido van Rossum95806091997-02-15 18:33:24 +000036TclError = _tkinter.TclError
Georg Brandl14fc4272008-05-17 18:39:55 +000037from tkinter.constants import *
Serhiy Storchakab1396522013-01-15 17:56:08 +020038import re
Guido van Rossum18468821994-06-20 07:49:28 +000039
Andrew Svetlova966c6f2012-03-21 23:52:59 +020040
Martin v. Löwis8c8aa5d2002-11-26 21:39:48 +000041wantobjects = 1
Martin v. Löwisffad6332002-11-26 09:28:05 +000042
Eric S. Raymondfc170b12001-02-09 11:51:27 +000043TkVersion = float(_tkinter.TK_VERSION)
44TclVersion = float(_tkinter.TCL_VERSION)
Guido van Rossum18468821994-06-20 07:49:28 +000045
Guido van Rossumd6615ab1997-08-05 02:35:01 +000046READABLE = _tkinter.READABLE
47WRITABLE = _tkinter.WRITABLE
48EXCEPTION = _tkinter.EXCEPTION
Guido van Rossumf53c86c1997-08-14 14:15:54 +000049
Fredrik Lundh06d28152000-08-09 18:03:12 +000050
Serhiy Storchakab1396522013-01-15 17:56:08 +020051_magic_re = re.compile(r'([\\{}])')
52_space_re = re.compile(r'([\s])', re.ASCII)
53
54def _join(value):
55 """Internal function."""
56 return ' '.join(map(_stringify, value))
57
58def _stringify(value):
59 """Internal function."""
60 if isinstance(value, (list, tuple)):
61 if len(value) == 1:
62 value = _stringify(value[0])
63 if value[0] == '{':
64 value = '{%s}' % value
65 else:
66 value = '{%s}' % _join(value)
67 else:
68 value = str(value)
69 if not value:
70 value = '{}'
71 elif _magic_re.search(value):
72 # add '\' before special characters and spaces
73 value = _magic_re.sub(r'\\\1', value)
74 value = _space_re.sub(r'\\\1', value)
75 elif value[0] == '"' or _space_re.search(value):
76 value = '{%s}' % value
77 return value
78
Guido van Rossum13257902007-06-07 23:15:56 +000079def _flatten(seq):
Fredrik Lundh06d28152000-08-09 18:03:12 +000080 """Internal function."""
81 res = ()
Guido van Rossum13257902007-06-07 23:15:56 +000082 for item in seq:
83 if isinstance(item, (tuple, list)):
Fredrik Lundh06d28152000-08-09 18:03:12 +000084 res = res + _flatten(item)
85 elif item is not None:
86 res = res + (item,)
87 return res
Guido van Rossum2dcf5291994-07-06 09:23:20 +000088
Andrew M. Kuchlinge475e702000-06-18 18:45:50 +000089try: _flatten = _tkinter._flatten
90except AttributeError: pass
91
Guido van Rossum2dcf5291994-07-06 09:23:20 +000092def _cnfmerge(cnfs):
Fredrik Lundh06d28152000-08-09 18:03:12 +000093 """Internal function."""
Guido van Rossum13257902007-06-07 23:15:56 +000094 if isinstance(cnfs, dict):
Fredrik Lundh06d28152000-08-09 18:03:12 +000095 return cnfs
Guido van Rossum13257902007-06-07 23:15:56 +000096 elif isinstance(cnfs, (type(None), str)):
Fredrik Lundh06d28152000-08-09 18:03:12 +000097 return cnfs
98 else:
99 cnf = {}
100 for c in _flatten(cnfs):
101 try:
102 cnf.update(c)
Guido van Rossumb940e112007-01-10 16:19:56 +0000103 except (AttributeError, TypeError) as msg:
Guido van Rossumbe19ed72007-02-09 05:37:30 +0000104 print("_cnfmerge: fallback due to:", msg)
Fredrik Lundh06d28152000-08-09 18:03:12 +0000105 for k, v in c.items():
106 cnf[k] = v
107 return cnf
Guido van Rossum2dcf5291994-07-06 09:23:20 +0000108
Andrew M. Kuchlinge475e702000-06-18 18:45:50 +0000109try: _cnfmerge = _tkinter._cnfmerge
110except AttributeError: pass
111
Serhiy Storchaka8f0a1d02014-09-06 22:47:58 +0300112def _splitdict(tk, v, cut_minus=True, conv=None):
113 """Return a properly formatted dict built from Tcl list pairs.
114
115 If cut_minus is True, the supposed '-' prefix will be removed from
116 keys. If conv is specified, it is used to convert values.
117
118 Tcl list is expected to contain an even number of elements.
119 """
120 t = tk.splitlist(v)
121 if len(t) % 2:
122 raise RuntimeError('Tcl list representing a dict is expected '
123 'to contain an even number of elements')
124 it = iter(t)
125 dict = {}
126 for key, value in zip(it, it):
127 key = str(key)
128 if cut_minus and key[0] == '-':
129 key = key[1:]
130 if conv:
131 value = conv(value)
132 dict[key] = value
133 return dict
134
Guido van Rossum2dcf5291994-07-06 09:23:20 +0000135class Event:
Fredrik Lundh06d28152000-08-09 18:03:12 +0000136 """Container for the properties of an event.
Guido van Rossum5917ecb2000-06-29 16:30:50 +0000137
Fredrik Lundh06d28152000-08-09 18:03:12 +0000138 Instances of this type are generated if one of the following events occurs:
Guido van Rossum5917ecb2000-06-29 16:30:50 +0000139
Fredrik Lundh06d28152000-08-09 18:03:12 +0000140 KeyPress, KeyRelease - for keyboard events
141 ButtonPress, ButtonRelease, Motion, Enter, Leave, MouseWheel - for mouse events
142 Visibility, Unmap, Map, Expose, FocusIn, FocusOut, Circulate,
143 Colormap, Gravity, Reparent, Property, Destroy, Activate,
144 Deactivate - for window events.
145
146 If a callback function for one of these events is registered
147 using bind, bind_all, bind_class, or tag_bind, the callback is
148 called with an Event as first argument. It will have the
149 following attributes (in braces are the event types for which
150 the attribute is valid):
151
Guido van Rossum5917ecb2000-06-29 16:30:50 +0000152 serial - serial number of event
Fredrik Lundh06d28152000-08-09 18:03:12 +0000153 num - mouse button pressed (ButtonPress, ButtonRelease)
154 focus - whether the window has the focus (Enter, Leave)
155 height - height of the exposed window (Configure, Expose)
156 width - width of the exposed window (Configure, Expose)
157 keycode - keycode of the pressed key (KeyPress, KeyRelease)
158 state - state of the event as a number (ButtonPress, ButtonRelease,
159 Enter, KeyPress, KeyRelease,
160 Leave, Motion)
161 state - state as a string (Visibility)
162 time - when the event occurred
163 x - x-position of the mouse
164 y - y-position of the mouse
165 x_root - x-position of the mouse on the screen
166 (ButtonPress, ButtonRelease, KeyPress, KeyRelease, Motion)
167 y_root - y-position of the mouse on the screen
168 (ButtonPress, ButtonRelease, KeyPress, KeyRelease, Motion)
169 char - pressed character (KeyPress, KeyRelease)
170 send_event - see X/Windows documentation
Walter Dörwald966c2642005-11-09 17:12:43 +0000171 keysym - keysym of the event as a string (KeyPress, KeyRelease)
Fredrik Lundh06d28152000-08-09 18:03:12 +0000172 keysym_num - keysym of the event as a number (KeyPress, KeyRelease)
173 type - type of the event as a number
174 widget - widget in which the event occurred
175 delta - delta of wheel movement (MouseWheel)
176 """
177 pass
Guido van Rossum2dcf5291994-07-06 09:23:20 +0000178
Guido van Rossumc4570481998-03-20 20:45:49 +0000179_support_default_root = 1
Guido van Rossumaec5dc91994-06-27 07:55:12 +0000180_default_root = None
181
Guido van Rossumc4570481998-03-20 20:45:49 +0000182def NoDefaultRoot():
Fredrik Lundh06d28152000-08-09 18:03:12 +0000183 """Inhibit setting of default root window.
Guido van Rossum5917ecb2000-06-29 16:30:50 +0000184
Fredrik Lundh06d28152000-08-09 18:03:12 +0000185 Call this function to inhibit that the first instance of
186 Tk is used for windows without an explicit parent window.
187 """
188 global _support_default_root
189 _support_default_root = 0
190 global _default_root
191 _default_root = None
192 del _default_root
Guido van Rossumc4570481998-03-20 20:45:49 +0000193
Guido van Rossum45853db1994-06-20 12:19:19 +0000194def _tkerror(err):
Fredrik Lundh06d28152000-08-09 18:03:12 +0000195 """Internal function."""
196 pass
Guido van Rossum18468821994-06-20 07:49:28 +0000197
Andrew Svetlov806bfad2012-12-10 00:02:31 +0200198def _exit(code=0):
Andrew Svetlov737fb892012-12-18 21:14:22 +0200199 """Internal function. Calling it will raise the exception SystemExit."""
Andrew Svetlov806bfad2012-12-10 00:02:31 +0200200 try:
201 code = int(code)
202 except ValueError:
203 pass
Collin Winterce36ad82007-08-30 01:19:48 +0000204 raise SystemExit(code)
Guido van Rossum97aeca11994-07-07 13:12:12 +0000205
Guido van Rossumaec5dc91994-06-27 07:55:12 +0000206_varnum = 0
207class Variable:
Guido van Rossum2cd0a652003-04-16 20:10:03 +0000208 """Class to define value holders for e.g. buttons.
209
210 Subclasses StringVar, IntVar, DoubleVar, BooleanVar are specializations
211 that constrain the type of the value returned from get()."""
Fredrik Lundh06d28152000-08-09 18:03:12 +0000212 _default = ""
Martin v. Löwis2b695a42012-03-12 17:47:35 -0700213 _tk = None
Serhiy Storchaka87bbf252014-08-17 15:31:59 +0300214 _tclCommands = None
Thomas Wouters0e3f5912006-08-11 14:57:12 +0000215 def __init__(self, master=None, value=None, name=None):
216 """Construct a variable
217
218 MASTER can be given as master widget.
219 VALUE is an optional value (defaults to "")
220 NAME is an optional Tcl name (defaults to PY_VARnum).
221
222 If NAME matches an existing variable and VALUE is omitted
223 then the existing value is retained.
Fredrik Lundh06d28152000-08-09 18:03:12 +0000224 """
Martin v. Löwis2b695a42012-03-12 17:47:35 -0700225 # check for type of NAME parameter to override weird error message
226 # raised from Modules/_tkinter.c:SetVar like:
227 # TypeError: setvar() takes exactly 3 arguments (2 given)
228 if name is not None and not isinstance(name, str):
229 raise TypeError("name must be a string")
Fredrik Lundh06d28152000-08-09 18:03:12 +0000230 global _varnum
231 if not master:
232 master = _default_root
Serhiy Storchaka87bbf252014-08-17 15:31:59 +0300233 self._root = master._root()
Fredrik Lundh06d28152000-08-09 18:03:12 +0000234 self._tk = master.tk
Thomas Wouters0e3f5912006-08-11 14:57:12 +0000235 if name:
236 self._name = name
237 else:
238 self._name = 'PY_VAR' + repr(_varnum)
239 _varnum += 1
Benjamin Peterson2a691a82008-03-31 01:51:45 +0000240 if value is not None:
Martin v. Löwis2b695a42012-03-12 17:47:35 -0700241 self.initialize(value)
Serhiy Storchakad97c01f2013-12-26 20:06:05 +0200242 elif not self._tk.getboolean(self._tk.call("info", "exists", self._name)):
Martin v. Löwis2b695a42012-03-12 17:47:35 -0700243 self.initialize(self._default)
Fredrik Lundh06d28152000-08-09 18:03:12 +0000244 def __del__(self):
245 """Unset the variable in Tcl."""
Serhiy Storchaka87bbf252014-08-17 15:31:59 +0300246 if self._tk is None:
247 return
248 if self._tk.getboolean(self._tk.call("info", "exists", self._name)):
Martin v. Löwis2b695a42012-03-12 17:47:35 -0700249 self._tk.globalunsetvar(self._name)
Serhiy Storchaka87bbf252014-08-17 15:31:59 +0300250 if self._tclCommands is not None:
251 for name in self._tclCommands:
252 #print '- Tkinter: deleted command', name
253 self._tk.deletecommand(name)
254 self._tclCommands = None
Fredrik Lundh06d28152000-08-09 18:03:12 +0000255 def __str__(self):
256 """Return the name of the variable in Tcl."""
257 return self._name
258 def set(self, value):
259 """Set the variable to VALUE."""
260 return self._tk.globalsetvar(self._name, value)
Martin v. Löwis2b695a42012-03-12 17:47:35 -0700261 initialize = set
Guido van Rossum2cd0a652003-04-16 20:10:03 +0000262 def get(self):
263 """Return value of variable."""
264 return self._tk.globalgetvar(self._name)
Fredrik Lundh06d28152000-08-09 18:03:12 +0000265 def trace_variable(self, mode, callback):
266 """Define a trace callback for the variable.
Guido van Rossum5917ecb2000-06-29 16:30:50 +0000267
Fredrik Lundh06d28152000-08-09 18:03:12 +0000268 MODE is one of "r", "w", "u" for read, write, undefine.
269 CALLBACK must be a function which is called when
270 the variable is read, written or undefined.
Guido van Rossum5917ecb2000-06-29 16:30:50 +0000271
Fredrik Lundh06d28152000-08-09 18:03:12 +0000272 Return the name of the callback.
273 """
Serhiy Storchaka87bbf252014-08-17 15:31:59 +0300274 f = CallWrapper(callback, None, self).__call__
275 cbname = repr(id(f))
276 try:
277 callback = callback.__func__
278 except AttributeError:
279 pass
280 try:
281 cbname = cbname + callback.__name__
282 except AttributeError:
283 pass
284 self._tk.createcommand(cbname, f)
285 if self._tclCommands is None:
286 self._tclCommands = []
287 self._tclCommands.append(cbname)
Serhiy Storchaka26f9feb2014-07-31 07:46:08 +0300288 self._tk.call("trace", "variable", self._name, mode, cbname)
Fredrik Lundh06d28152000-08-09 18:03:12 +0000289 return cbname
290 trace = trace_variable
291 def trace_vdelete(self, mode, cbname):
292 """Delete the trace callback for a variable.
Guido van Rossum5917ecb2000-06-29 16:30:50 +0000293
Fredrik Lundh06d28152000-08-09 18:03:12 +0000294 MODE is one of "r", "w", "u" for read, write, undefine.
295 CBNAME is the name of the callback returned from trace_variable or trace.
296 """
Serhiy Storchaka26f9feb2014-07-31 07:46:08 +0300297 self._tk.call("trace", "vdelete", self._name, mode, cbname)
Serhiy Storchaka87bbf252014-08-17 15:31:59 +0300298 self._tk.deletecommand(cbname)
299 try:
300 self._tclCommands.remove(cbname)
301 except ValueError:
302 pass
Fredrik Lundh06d28152000-08-09 18:03:12 +0000303 def trace_vinfo(self):
304 """Return all trace callback information."""
Alexander Belopolsky022f0492010-11-22 19:40:51 +0000305 return [self._tk.split(x) for x in self._tk.splitlist(
Serhiy Storchaka26f9feb2014-07-31 07:46:08 +0300306 self._tk.call("trace", "vinfo", self._name))]
Thomas Wouters0e3f5912006-08-11 14:57:12 +0000307 def __eq__(self, other):
308 """Comparison for equality (==).
309
310 Note: if the Variable's master matters to behavior
311 also compare self._master == other._master
312 """
313 return self.__class__.__name__ == other.__class__.__name__ \
314 and self._name == other._name
Guido van Rossumaec5dc91994-06-27 07:55:12 +0000315
316class StringVar(Variable):
Fredrik Lundh06d28152000-08-09 18:03:12 +0000317 """Value holder for strings variables."""
318 _default = ""
Thomas Wouters0e3f5912006-08-11 14:57:12 +0000319 def __init__(self, master=None, value=None, name=None):
Fredrik Lundh06d28152000-08-09 18:03:12 +0000320 """Construct a string variable.
Guido van Rossum5917ecb2000-06-29 16:30:50 +0000321
Thomas Wouters0e3f5912006-08-11 14:57:12 +0000322 MASTER can be given as master widget.
323 VALUE is an optional value (defaults to "")
324 NAME is an optional Tcl name (defaults to PY_VARnum).
325
326 If NAME matches an existing variable and VALUE is omitted
327 then the existing value is retained.
328 """
329 Variable.__init__(self, master, value, name)
Guido van Rossum5917ecb2000-06-29 16:30:50 +0000330
Fredrik Lundh06d28152000-08-09 18:03:12 +0000331 def get(self):
332 """Return value of variable as string."""
Martin v. Löwisbfe175c2003-04-16 19:42:51 +0000333 value = self._tk.globalgetvar(self._name)
Guido van Rossum3172c5d2007-10-16 18:12:55 +0000334 if isinstance(value, str):
Martin v. Löwisbfe175c2003-04-16 19:42:51 +0000335 return value
336 return str(value)
Guido van Rossumaec5dc91994-06-27 07:55:12 +0000337
338class IntVar(Variable):
Fredrik Lundh06d28152000-08-09 18:03:12 +0000339 """Value holder for integer variables."""
340 _default = 0
Thomas Wouters0e3f5912006-08-11 14:57:12 +0000341 def __init__(self, master=None, value=None, name=None):
Fredrik Lundh06d28152000-08-09 18:03:12 +0000342 """Construct an integer variable.
Guido van Rossum5917ecb2000-06-29 16:30:50 +0000343
Thomas Wouters0e3f5912006-08-11 14:57:12 +0000344 MASTER can be given as master widget.
345 VALUE is an optional value (defaults to 0)
346 NAME is an optional Tcl name (defaults to PY_VARnum).
347
348 If NAME matches an existing variable and VALUE is omitted
349 then the existing value is retained.
350 """
351 Variable.__init__(self, master, value, name)
Guido van Rossum5917ecb2000-06-29 16:30:50 +0000352
Fredrik Lundh06d28152000-08-09 18:03:12 +0000353 def get(self):
354 """Return the value of the variable as an integer."""
Serhiy Storchaka645058d2015-05-06 14:00:04 +0300355 return self._tk.getint(self._tk.globalgetvar(self._name))
Guido van Rossumaec5dc91994-06-27 07:55:12 +0000356
357class DoubleVar(Variable):
Fredrik Lundh06d28152000-08-09 18:03:12 +0000358 """Value holder for float variables."""
359 _default = 0.0
Thomas Wouters0e3f5912006-08-11 14:57:12 +0000360 def __init__(self, master=None, value=None, name=None):
Fredrik Lundh06d28152000-08-09 18:03:12 +0000361 """Construct a float variable.
Guido van Rossum5917ecb2000-06-29 16:30:50 +0000362
Thomas Wouters0e3f5912006-08-11 14:57:12 +0000363 MASTER can be given as master widget.
364 VALUE is an optional value (defaults to 0.0)
365 NAME is an optional Tcl name (defaults to PY_VARnum).
366
367 If NAME matches an existing variable and VALUE is omitted
368 then the existing value is retained.
369 """
370 Variable.__init__(self, master, value, name)
Fredrik Lundh06d28152000-08-09 18:03:12 +0000371
372 def get(self):
373 """Return the value of the variable as a float."""
Serhiy Storchaka645058d2015-05-06 14:00:04 +0300374 return self._tk.getdouble(self._tk.globalgetvar(self._name))
Guido van Rossumaec5dc91994-06-27 07:55:12 +0000375
376class BooleanVar(Variable):
Fredrik Lundh06d28152000-08-09 18:03:12 +0000377 """Value holder for boolean variables."""
Thomas Wouters0e3f5912006-08-11 14:57:12 +0000378 _default = False
379 def __init__(self, master=None, value=None, name=None):
Fredrik Lundh06d28152000-08-09 18:03:12 +0000380 """Construct a boolean variable.
Guido van Rossum5917ecb2000-06-29 16:30:50 +0000381
Thomas Wouters0e3f5912006-08-11 14:57:12 +0000382 MASTER can be given as master widget.
383 VALUE is an optional value (defaults to False)
384 NAME is an optional Tcl name (defaults to PY_VARnum).
385
386 If NAME matches an existing variable and VALUE is omitted
387 then the existing value is retained.
388 """
389 Variable.__init__(self, master, value, name)
Guido van Rossum5917ecb2000-06-29 16:30:50 +0000390
Serhiy Storchaka9a6e2012015-04-04 12:43:01 +0300391 def set(self, value):
392 """Set the variable to VALUE."""
393 return self._tk.globalsetvar(self._name, self._tk.getboolean(value))
394 initialize = set
395
Fredrik Lundh06d28152000-08-09 18:03:12 +0000396 def get(self):
Martin v. Löwisbfe175c2003-04-16 19:42:51 +0000397 """Return the value of the variable as a bool."""
Martin v. Löwis2b695a42012-03-12 17:47:35 -0700398 try:
399 return self._tk.getboolean(self._tk.globalgetvar(self._name))
400 except TclError:
401 raise ValueError("invalid literal for getboolean()")
Guido van Rossumaec5dc91994-06-27 07:55:12 +0000402
Guido van Rossum35f67fb1995-08-04 03:50:29 +0000403def mainloop(n=0):
Fredrik Lundh06d28152000-08-09 18:03:12 +0000404 """Run the main loop of Tcl."""
405 _default_root.tk.mainloop(n)
Guido van Rossum2dcf5291994-07-06 09:23:20 +0000406
Guido van Rossum0132f691998-04-30 17:50:36 +0000407getint = int
Guido van Rossum2dcf5291994-07-06 09:23:20 +0000408
Guido van Rossum0132f691998-04-30 17:50:36 +0000409getdouble = float
Guido van Rossum2dcf5291994-07-06 09:23:20 +0000410
411def getboolean(s):
Fredrik Lundh06d28152000-08-09 18:03:12 +0000412 """Convert true and false to integer values 1 and 0."""
Martin v. Löwis2b695a42012-03-12 17:47:35 -0700413 try:
414 return _default_root.tk.getboolean(s)
415 except TclError:
416 raise ValueError("invalid literal for getboolean()")
Guido van Rossum2dcf5291994-07-06 09:23:20 +0000417
Guido van Rossum368e06b1997-11-07 20:38:49 +0000418# Methods defined on both toplevel and interior widgets
Guido van Rossum18468821994-06-20 07:49:28 +0000419class Misc:
Fredrik Lundh06d28152000-08-09 18:03:12 +0000420 """Internal class.
Guido van Rossum5917ecb2000-06-29 16:30:50 +0000421
Fredrik Lundh06d28152000-08-09 18:03:12 +0000422 Base class which defines methods common for interior widgets."""
Guido van Rossum5917ecb2000-06-29 16:30:50 +0000423
Fredrik Lundh06d28152000-08-09 18:03:12 +0000424 # XXX font command?
425 _tclCommands = None
426 def destroy(self):
427 """Internal function.
Guido van Rossum5917ecb2000-06-29 16:30:50 +0000428
Fredrik Lundh06d28152000-08-09 18:03:12 +0000429 Delete all Tcl commands created for
430 this widget in the Tcl interpreter."""
431 if self._tclCommands is not None:
432 for name in self._tclCommands:
433 #print '- Tkinter: deleted command', name
434 self.tk.deletecommand(name)
435 self._tclCommands = None
436 def deletecommand(self, name):
437 """Internal function.
Guido van Rossum5917ecb2000-06-29 16:30:50 +0000438
Fredrik Lundh06d28152000-08-09 18:03:12 +0000439 Delete the Tcl command provided in NAME."""
440 #print '- Tkinter: deleted command', name
441 self.tk.deletecommand(name)
442 try:
443 self._tclCommands.remove(name)
444 except ValueError:
445 pass
446 def tk_strictMotif(self, boolean=None):
447 """Set Tcl internal variable, whether the look and feel
448 should adhere to Motif.
Guido van Rossum5917ecb2000-06-29 16:30:50 +0000449
Fredrik Lundh06d28152000-08-09 18:03:12 +0000450 A parameter of 1 means adhere to Motif (e.g. no color
451 change if mouse passes over slider).
452 Returns the set value."""
453 return self.tk.getboolean(self.tk.call(
454 'set', 'tk_strictMotif', boolean))
455 def tk_bisque(self):
456 """Change the color scheme to light brown as used in Tk 3.6 and before."""
457 self.tk.call('tk_bisque')
458 def tk_setPalette(self, *args, **kw):
459 """Set a new color scheme for all widget elements.
Guido van Rossum5917ecb2000-06-29 16:30:50 +0000460
Fredrik Lundh06d28152000-08-09 18:03:12 +0000461 A single color as argument will cause that all colors of Tk
462 widget elements are derived from this.
463 Alternatively several keyword parameters and its associated
464 colors can be given. The following keywords are valid:
465 activeBackground, foreground, selectColor,
466 activeForeground, highlightBackground, selectBackground,
467 background, highlightColor, selectForeground,
468 disabledForeground, insertBackground, troughColor."""
469 self.tk.call(('tk_setPalette',)
Serhiy Storchaka4cf4f3a2013-01-02 00:03:58 +0200470 + _flatten(args) + _flatten(list(kw.items())))
Fredrik Lundh06d28152000-08-09 18:03:12 +0000471 def tk_menuBar(self, *args):
472 """Do not use. Needed in Tk 3.6 and earlier."""
Serhiy Storchaka1a901cc2014-07-25 12:24:07 +0300473 # obsolete since Tk 4.0
474 import warnings
475 warnings.warn('tk_menuBar() does nothing and will be removed in 3.6',
476 DeprecationWarning, stacklevel=2)
Fredrik Lundh06d28152000-08-09 18:03:12 +0000477 def wait_variable(self, name='PY_VAR'):
478 """Wait until the variable is modified.
Guido van Rossum5917ecb2000-06-29 16:30:50 +0000479
Fredrik Lundh06d28152000-08-09 18:03:12 +0000480 A parameter of type IntVar, StringVar, DoubleVar or
481 BooleanVar must be given."""
482 self.tk.call('tkwait', 'variable', name)
483 waitvar = wait_variable # XXX b/w compat
484 def wait_window(self, window=None):
485 """Wait until a WIDGET is destroyed.
Guido van Rossum5917ecb2000-06-29 16:30:50 +0000486
Fredrik Lundh06d28152000-08-09 18:03:12 +0000487 If no parameter is given self is used."""
Fred Drake132dce22000-12-12 23:11:42 +0000488 if window is None:
Fredrik Lundh06d28152000-08-09 18:03:12 +0000489 window = self
490 self.tk.call('tkwait', 'window', window._w)
491 def wait_visibility(self, window=None):
492 """Wait until the visibility of a WIDGET changes
493 (e.g. it appears).
Guido van Rossum5917ecb2000-06-29 16:30:50 +0000494
Fredrik Lundh06d28152000-08-09 18:03:12 +0000495 If no parameter is given self is used."""
Fred Drake132dce22000-12-12 23:11:42 +0000496 if window is None:
Fredrik Lundh06d28152000-08-09 18:03:12 +0000497 window = self
498 self.tk.call('tkwait', 'visibility', window._w)
499 def setvar(self, name='PY_VAR', value='1'):
500 """Set Tcl variable NAME to VALUE."""
501 self.tk.setvar(name, value)
502 def getvar(self, name='PY_VAR'):
503 """Return value of Tcl variable NAME."""
504 return self.tk.getvar(name)
Serhiy Storchaka645058d2015-05-06 14:00:04 +0300505
506 def getint(self, s):
507 try:
508 return self.tk.getint(s)
509 except TclError as exc:
510 raise ValueError(str(exc))
511
512 def getdouble(self, s):
513 try:
514 return self.tk.getdouble(s)
515 except TclError as exc:
516 raise ValueError(str(exc))
517
Fredrik Lundh06d28152000-08-09 18:03:12 +0000518 def getboolean(self, s):
Neal Norwitz6e5be222003-04-17 13:13:55 +0000519 """Return a boolean value for Tcl boolean values true and false given as parameter."""
Martin v. Löwis2b695a42012-03-12 17:47:35 -0700520 try:
521 return self.tk.getboolean(s)
522 except TclError:
523 raise ValueError("invalid literal for getboolean()")
Serhiy Storchaka645058d2015-05-06 14:00:04 +0300524
Fredrik Lundh06d28152000-08-09 18:03:12 +0000525 def focus_set(self):
526 """Direct input focus to this widget.
Guido van Rossum5917ecb2000-06-29 16:30:50 +0000527
Fredrik Lundh06d28152000-08-09 18:03:12 +0000528 If the application currently does not have the focus
529 this widget will get the focus if the application gets
530 the focus through the window manager."""
531 self.tk.call('focus', self._w)
532 focus = focus_set # XXX b/w compat?
533 def focus_force(self):
534 """Direct input focus to this widget even if the
535 application does not have the focus. Use with
536 caution!"""
537 self.tk.call('focus', '-force', self._w)
538 def focus_get(self):
539 """Return the widget which has currently the focus in the
540 application.
Guido van Rossum5917ecb2000-06-29 16:30:50 +0000541
Fredrik Lundh06d28152000-08-09 18:03:12 +0000542 Use focus_displayof to allow working with several
543 displays. Return None if application does not have
544 the focus."""
545 name = self.tk.call('focus')
546 if name == 'none' or not name: return None
547 return self._nametowidget(name)
548 def focus_displayof(self):
549 """Return the widget which has currently the focus on the
550 display where this widget is located.
Guido van Rossum5917ecb2000-06-29 16:30:50 +0000551
Fredrik Lundh06d28152000-08-09 18:03:12 +0000552 Return None if the application does not have the focus."""
553 name = self.tk.call('focus', '-displayof', self._w)
554 if name == 'none' or not name: return None
555 return self._nametowidget(name)
556 def focus_lastfor(self):
557 """Return the widget which would have the focus if top level
558 for this widget gets the focus from the window manager."""
559 name = self.tk.call('focus', '-lastfor', self._w)
560 if name == 'none' or not name: return None
561 return self._nametowidget(name)
562 def tk_focusFollowsMouse(self):
563 """The widget under mouse will get automatically focus. Can not
564 be disabled easily."""
565 self.tk.call('tk_focusFollowsMouse')
566 def tk_focusNext(self):
567 """Return the next widget in the focus order which follows
568 widget which has currently the focus.
Guido van Rossum5917ecb2000-06-29 16:30:50 +0000569
Fredrik Lundh06d28152000-08-09 18:03:12 +0000570 The focus order first goes to the next child, then to
571 the children of the child recursively and then to the
572 next sibling which is higher in the stacking order. A
573 widget is omitted if it has the takefocus resource set
574 to 0."""
575 name = self.tk.call('tk_focusNext', self._w)
576 if not name: return None
577 return self._nametowidget(name)
578 def tk_focusPrev(self):
579 """Return previous widget in the focus order. See tk_focusNext for details."""
580 name = self.tk.call('tk_focusPrev', self._w)
581 if not name: return None
582 return self._nametowidget(name)
583 def after(self, ms, func=None, *args):
584 """Call function once after given time.
Guido van Rossum5917ecb2000-06-29 16:30:50 +0000585
Fredrik Lundh06d28152000-08-09 18:03:12 +0000586 MS specifies the time in milliseconds. FUNC gives the
587 function which shall be called. Additional parameters
588 are given as parameters to the function call. Return
589 identifier to cancel scheduling with after_cancel."""
590 if not func:
591 # I'd rather use time.sleep(ms*0.001)
592 self.tk.call('after', ms)
593 else:
Thomas Wouters49fd7fa2006-04-21 10:40:58 +0000594 def callit():
Fredrik Lundh06d28152000-08-09 18:03:12 +0000595 try:
Raymond Hettingerff41c482003-04-06 09:01:11 +0000596 func(*args)
Fredrik Lundh06d28152000-08-09 18:03:12 +0000597 finally:
598 try:
Thomas Wouters49fd7fa2006-04-21 10:40:58 +0000599 self.deletecommand(name)
Fredrik Lundh06d28152000-08-09 18:03:12 +0000600 except TclError:
601 pass
Serhiy Storchakad00aff22014-08-24 09:07:47 +0300602 callit.__name__ = func.__name__
Fredrik Lundh06d28152000-08-09 18:03:12 +0000603 name = self._register(callit)
Fredrik Lundh06d28152000-08-09 18:03:12 +0000604 return self.tk.call('after', ms, name)
605 def after_idle(self, func, *args):
606 """Call FUNC once if the Tcl main loop has no event to
607 process.
Guido van Rossum5917ecb2000-06-29 16:30:50 +0000608
Fredrik Lundh06d28152000-08-09 18:03:12 +0000609 Return an identifier to cancel the scheduling with
610 after_cancel."""
Raymond Hettingerff41c482003-04-06 09:01:11 +0000611 return self.after('idle', func, *args)
Fredrik Lundh06d28152000-08-09 18:03:12 +0000612 def after_cancel(self, id):
613 """Cancel scheduling of function identified with ID.
Guido van Rossum5917ecb2000-06-29 16:30:50 +0000614
Fredrik Lundh06d28152000-08-09 18:03:12 +0000615 Identifier returned by after or after_idle must be
616 given as first parameter."""
Martin v. Löwis0f9e5252003-06-07 19:52:38 +0000617 try:
Neal Norwitz3c0f2c92003-07-01 21:12:47 +0000618 data = self.tk.call('after', 'info', id)
619 # In Tk 8.3, splitlist returns: (script, type)
620 # In Tk 8.4, splitlist may return (script, type) or (script,)
621 script = self.tk.splitlist(data)[0]
Martin v. Löwis0f9e5252003-06-07 19:52:38 +0000622 self.deletecommand(script)
623 except TclError:
624 pass
Fredrik Lundh06d28152000-08-09 18:03:12 +0000625 self.tk.call('after', 'cancel', id)
626 def bell(self, displayof=0):
627 """Ring a display's bell."""
628 self.tk.call(('bell',) + self._displayof(displayof))
Thomas Wouters49fd7fa2006-04-21 10:40:58 +0000629
Fredrik Lundh06d28152000-08-09 18:03:12 +0000630 # Clipboard handling:
Thomas Wouters49fd7fa2006-04-21 10:40:58 +0000631 def clipboard_get(self, **kw):
632 """Retrieve data from the clipboard on window's display.
633
634 The window keyword defaults to the root window of the Tkinter
635 application.
636
637 The type keyword specifies the form in which the data is
638 to be returned and should be an atom name such as STRING
Ned Deily4d377d92012-05-15 18:08:11 -0700639 or FILE_NAME. Type defaults to STRING, except on X11, where the default
640 is to try UTF8_STRING and fall back to STRING.
Thomas Wouters49fd7fa2006-04-21 10:40:58 +0000641
642 This command is equivalent to:
643
644 selection_get(CLIPBOARD)
645 """
Ned Deily4d377d92012-05-15 18:08:11 -0700646 if 'type' not in kw and self._windowingsystem == 'x11':
647 try:
648 kw['type'] = 'UTF8_STRING'
649 return self.tk.call(('clipboard', 'get') + self._options(kw))
650 except TclError:
651 del kw['type']
Thomas Wouters49fd7fa2006-04-21 10:40:58 +0000652 return self.tk.call(('clipboard', 'get') + self._options(kw))
653
Fredrik Lundh06d28152000-08-09 18:03:12 +0000654 def clipboard_clear(self, **kw):
655 """Clear the data in the Tk clipboard.
Guido van Rossum5917ecb2000-06-29 16:30:50 +0000656
Fredrik Lundh06d28152000-08-09 18:03:12 +0000657 A widget specified for the optional displayof keyword
658 argument specifies the target display."""
Guido van Rossume014a132006-08-19 16:53:45 +0000659 if 'displayof' not in kw: kw['displayof'] = self._w
Fredrik Lundh06d28152000-08-09 18:03:12 +0000660 self.tk.call(('clipboard', 'clear') + self._options(kw))
661 def clipboard_append(self, string, **kw):
662 """Append STRING to the Tk clipboard.
Guido van Rossum5917ecb2000-06-29 16:30:50 +0000663
Fredrik Lundh06d28152000-08-09 18:03:12 +0000664 A widget specified at the optional displayof keyword
665 argument specifies the target display. The clipboard
666 can be retrieved with selection_get."""
Guido van Rossume014a132006-08-19 16:53:45 +0000667 if 'displayof' not in kw: kw['displayof'] = self._w
Fredrik Lundh06d28152000-08-09 18:03:12 +0000668 self.tk.call(('clipboard', 'append') + self._options(kw)
669 + ('--', string))
670 # XXX grab current w/o window argument
671 def grab_current(self):
672 """Return widget which has currently the grab in this application
673 or None."""
674 name = self.tk.call('grab', 'current', self._w)
675 if not name: return None
676 return self._nametowidget(name)
677 def grab_release(self):
678 """Release grab for this widget if currently set."""
679 self.tk.call('grab', 'release', self._w)
680 def grab_set(self):
681 """Set grab for this widget.
Guido van Rossum5917ecb2000-06-29 16:30:50 +0000682
Fredrik Lundh06d28152000-08-09 18:03:12 +0000683 A grab directs all events to this and descendant
684 widgets in the application."""
685 self.tk.call('grab', 'set', self._w)
686 def grab_set_global(self):
687 """Set global grab for this widget.
Guido van Rossum5917ecb2000-06-29 16:30:50 +0000688
Fredrik Lundh06d28152000-08-09 18:03:12 +0000689 A global grab directs all events to this and
690 descendant widgets on the display. Use with caution -
691 other applications do not get events anymore."""
692 self.tk.call('grab', 'set', '-global', self._w)
693 def grab_status(self):
694 """Return None, "local" or "global" if this widget has
695 no, a local or a global grab."""
696 status = self.tk.call('grab', 'status', self._w)
697 if status == 'none': status = None
698 return status
Fredrik Lundh06d28152000-08-09 18:03:12 +0000699 def option_add(self, pattern, value, priority = None):
700 """Set a VALUE (second parameter) for an option
701 PATTERN (first parameter).
Guido van Rossum5917ecb2000-06-29 16:30:50 +0000702
Fredrik Lundh06d28152000-08-09 18:03:12 +0000703 An optional third parameter gives the numeric priority
704 (defaults to 80)."""
705 self.tk.call('option', 'add', pattern, value, priority)
706 def option_clear(self):
707 """Clear the option database.
Guido van Rossum5917ecb2000-06-29 16:30:50 +0000708
Fredrik Lundh06d28152000-08-09 18:03:12 +0000709 It will be reloaded if option_add is called."""
710 self.tk.call('option', 'clear')
711 def option_get(self, name, className):
712 """Return the value for an option NAME for this widget
713 with CLASSNAME.
Guido van Rossum5917ecb2000-06-29 16:30:50 +0000714
Fredrik Lundh06d28152000-08-09 18:03:12 +0000715 Values with higher priority override lower values."""
716 return self.tk.call('option', 'get', self._w, name, className)
717 def option_readfile(self, fileName, priority = None):
718 """Read file FILENAME into the option database.
Guido van Rossum5917ecb2000-06-29 16:30:50 +0000719
Fredrik Lundh06d28152000-08-09 18:03:12 +0000720 An optional second parameter gives the numeric
721 priority."""
722 self.tk.call('option', 'readfile', fileName, priority)
723 def selection_clear(self, **kw):
724 """Clear the current X selection."""
Guido van Rossume014a132006-08-19 16:53:45 +0000725 if 'displayof' not in kw: kw['displayof'] = self._w
Fredrik Lundh06d28152000-08-09 18:03:12 +0000726 self.tk.call(('selection', 'clear') + self._options(kw))
727 def selection_get(self, **kw):
728 """Return the contents of the current X selection.
Guido van Rossum5917ecb2000-06-29 16:30:50 +0000729
Fredrik Lundh06d28152000-08-09 18:03:12 +0000730 A keyword parameter selection specifies the name of
731 the selection and defaults to PRIMARY. A keyword
732 parameter displayof specifies a widget on the display
Ned Deily4d377d92012-05-15 18:08:11 -0700733 to use. A keyword parameter type specifies the form of data to be
734 fetched, defaulting to STRING except on X11, where UTF8_STRING is tried
735 before STRING."""
Guido van Rossume014a132006-08-19 16:53:45 +0000736 if 'displayof' not in kw: kw['displayof'] = self._w
Ned Deily4d377d92012-05-15 18:08:11 -0700737 if 'type' not in kw and self._windowingsystem == 'x11':
738 try:
739 kw['type'] = 'UTF8_STRING'
740 return self.tk.call(('selection', 'get') + self._options(kw))
741 except TclError:
742 del kw['type']
Fredrik Lundh06d28152000-08-09 18:03:12 +0000743 return self.tk.call(('selection', 'get') + self._options(kw))
744 def selection_handle(self, command, **kw):
745 """Specify a function COMMAND to call if the X
746 selection owned by this widget is queried by another
747 application.
Guido van Rossum5917ecb2000-06-29 16:30:50 +0000748
Fredrik Lundh06d28152000-08-09 18:03:12 +0000749 This function must return the contents of the
750 selection. The function will be called with the
751 arguments OFFSET and LENGTH which allows the chunking
752 of very long selections. The following keyword
753 parameters can be provided:
754 selection - name of the selection (default PRIMARY),
755 type - type of the selection (e.g. STRING, FILE_NAME)."""
756 name = self._register(command)
757 self.tk.call(('selection', 'handle') + self._options(kw)
758 + (self._w, name))
759 def selection_own(self, **kw):
760 """Become owner of X selection.
Guido van Rossum5917ecb2000-06-29 16:30:50 +0000761
Fredrik Lundh06d28152000-08-09 18:03:12 +0000762 A keyword parameter selection specifies the name of
763 the selection (default PRIMARY)."""
764 self.tk.call(('selection', 'own') +
765 self._options(kw) + (self._w,))
766 def selection_own_get(self, **kw):
767 """Return owner of X selection.
Guido van Rossum5917ecb2000-06-29 16:30:50 +0000768
Fredrik Lundh06d28152000-08-09 18:03:12 +0000769 The following keyword parameter can
770 be provided:
771 selection - name of the selection (default PRIMARY),
772 type - type of the selection (e.g. STRING, FILE_NAME)."""
Guido van Rossume014a132006-08-19 16:53:45 +0000773 if 'displayof' not in kw: kw['displayof'] = self._w
Fredrik Lundh06d28152000-08-09 18:03:12 +0000774 name = self.tk.call(('selection', 'own') + self._options(kw))
775 if not name: return None
776 return self._nametowidget(name)
777 def send(self, interp, cmd, *args):
778 """Send Tcl command CMD to different interpreter INTERP to be executed."""
779 return self.tk.call(('send', interp, cmd) + args)
780 def lower(self, belowThis=None):
781 """Lower this widget in the stacking order."""
782 self.tk.call('lower', self._w, belowThis)
783 def tkraise(self, aboveThis=None):
784 """Raise this widget in the stacking order."""
785 self.tk.call('raise', self._w, aboveThis)
786 lift = tkraise
Fredrik Lundh06d28152000-08-09 18:03:12 +0000787 def winfo_atom(self, name, displayof=0):
788 """Return integer which represents atom NAME."""
789 args = ('winfo', 'atom') + self._displayof(displayof) + (name,)
Serhiy Storchaka645058d2015-05-06 14:00:04 +0300790 return self.tk.getint(self.tk.call(args))
Fredrik Lundh06d28152000-08-09 18:03:12 +0000791 def winfo_atomname(self, id, displayof=0):
792 """Return name of atom with identifier ID."""
793 args = ('winfo', 'atomname') \
794 + self._displayof(displayof) + (id,)
795 return self.tk.call(args)
796 def winfo_cells(self):
797 """Return number of cells in the colormap for this widget."""
Serhiy Storchaka645058d2015-05-06 14:00:04 +0300798 return self.tk.getint(
Fredrik Lundh06d28152000-08-09 18:03:12 +0000799 self.tk.call('winfo', 'cells', self._w))
800 def winfo_children(self):
801 """Return a list of all widgets which are children of this widget."""
Martin v. Löwisf2041b82002-03-27 17:15:57 +0000802 result = []
803 for child in self.tk.splitlist(
804 self.tk.call('winfo', 'children', self._w)):
805 try:
806 # Tcl sometimes returns extra windows, e.g. for
807 # menus; those need to be skipped
808 result.append(self._nametowidget(child))
809 except KeyError:
810 pass
811 return result
812
Fredrik Lundh06d28152000-08-09 18:03:12 +0000813 def winfo_class(self):
814 """Return window class name of this widget."""
815 return self.tk.call('winfo', 'class', self._w)
816 def winfo_colormapfull(self):
817 """Return true if at the last color request the colormap was full."""
818 return self.tk.getboolean(
819 self.tk.call('winfo', 'colormapfull', self._w))
820 def winfo_containing(self, rootX, rootY, displayof=0):
821 """Return the widget which is at the root coordinates ROOTX, ROOTY."""
822 args = ('winfo', 'containing') \
823 + self._displayof(displayof) + (rootX, rootY)
824 name = self.tk.call(args)
825 if not name: return None
826 return self._nametowidget(name)
827 def winfo_depth(self):
828 """Return the number of bits per pixel."""
Serhiy Storchaka645058d2015-05-06 14:00:04 +0300829 return self.tk.getint(self.tk.call('winfo', 'depth', self._w))
Fredrik Lundh06d28152000-08-09 18:03:12 +0000830 def winfo_exists(self):
831 """Return true if this widget exists."""
Serhiy Storchaka645058d2015-05-06 14:00:04 +0300832 return self.tk.getint(
Fredrik Lundh06d28152000-08-09 18:03:12 +0000833 self.tk.call('winfo', 'exists', self._w))
834 def winfo_fpixels(self, number):
835 """Return the number of pixels for the given distance NUMBER
836 (e.g. "3c") as float."""
Serhiy Storchaka645058d2015-05-06 14:00:04 +0300837 return self.tk.getdouble(self.tk.call(
Fredrik Lundh06d28152000-08-09 18:03:12 +0000838 'winfo', 'fpixels', self._w, number))
839 def winfo_geometry(self):
840 """Return geometry string for this widget in the form "widthxheight+X+Y"."""
841 return self.tk.call('winfo', 'geometry', self._w)
842 def winfo_height(self):
843 """Return height of this widget."""
Serhiy Storchaka645058d2015-05-06 14:00:04 +0300844 return self.tk.getint(
Fredrik Lundh06d28152000-08-09 18:03:12 +0000845 self.tk.call('winfo', 'height', self._w))
846 def winfo_id(self):
847 """Return identifier ID for this widget."""
848 return self.tk.getint(
849 self.tk.call('winfo', 'id', self._w))
850 def winfo_interps(self, displayof=0):
851 """Return the name of all Tcl interpreters for this display."""
852 args = ('winfo', 'interps') + self._displayof(displayof)
853 return self.tk.splitlist(self.tk.call(args))
854 def winfo_ismapped(self):
855 """Return true if this widget is mapped."""
Serhiy Storchaka645058d2015-05-06 14:00:04 +0300856 return self.tk.getint(
Fredrik Lundh06d28152000-08-09 18:03:12 +0000857 self.tk.call('winfo', 'ismapped', self._w))
858 def winfo_manager(self):
859 """Return the window mananger name for this widget."""
860 return self.tk.call('winfo', 'manager', self._w)
861 def winfo_name(self):
862 """Return the name of this widget."""
863 return self.tk.call('winfo', 'name', self._w)
864 def winfo_parent(self):
865 """Return the name of the parent of this widget."""
866 return self.tk.call('winfo', 'parent', self._w)
867 def winfo_pathname(self, id, displayof=0):
868 """Return the pathname of the widget given by ID."""
869 args = ('winfo', 'pathname') \
870 + self._displayof(displayof) + (id,)
871 return self.tk.call(args)
872 def winfo_pixels(self, number):
873 """Rounded integer value of winfo_fpixels."""
Serhiy Storchaka645058d2015-05-06 14:00:04 +0300874 return self.tk.getint(
Fredrik Lundh06d28152000-08-09 18:03:12 +0000875 self.tk.call('winfo', 'pixels', self._w, number))
876 def winfo_pointerx(self):
877 """Return the x coordinate of the pointer on the root window."""
Serhiy Storchaka645058d2015-05-06 14:00:04 +0300878 return self.tk.getint(
Fredrik Lundh06d28152000-08-09 18:03:12 +0000879 self.tk.call('winfo', 'pointerx', self._w))
880 def winfo_pointerxy(self):
881 """Return a tuple of x and y coordinates of the pointer on the root window."""
882 return self._getints(
883 self.tk.call('winfo', 'pointerxy', self._w))
884 def winfo_pointery(self):
885 """Return the y coordinate of the pointer on the root window."""
Serhiy Storchaka645058d2015-05-06 14:00:04 +0300886 return self.tk.getint(
Fredrik Lundh06d28152000-08-09 18:03:12 +0000887 self.tk.call('winfo', 'pointery', self._w))
888 def winfo_reqheight(self):
889 """Return requested height of this widget."""
Serhiy Storchaka645058d2015-05-06 14:00:04 +0300890 return self.tk.getint(
Fredrik Lundh06d28152000-08-09 18:03:12 +0000891 self.tk.call('winfo', 'reqheight', self._w))
892 def winfo_reqwidth(self):
893 """Return requested width of this widget."""
Serhiy Storchaka645058d2015-05-06 14:00:04 +0300894 return self.tk.getint(
Fredrik Lundh06d28152000-08-09 18:03:12 +0000895 self.tk.call('winfo', 'reqwidth', self._w))
896 def winfo_rgb(self, color):
897 """Return tuple of decimal values for red, green, blue for
898 COLOR in this widget."""
899 return self._getints(
900 self.tk.call('winfo', 'rgb', self._w, color))
901 def winfo_rootx(self):
902 """Return x coordinate of upper left corner of this widget on the
903 root window."""
Serhiy Storchaka645058d2015-05-06 14:00:04 +0300904 return self.tk.getint(
Fredrik Lundh06d28152000-08-09 18:03:12 +0000905 self.tk.call('winfo', 'rootx', self._w))
906 def winfo_rooty(self):
907 """Return y coordinate of upper left corner of this widget on the
908 root window."""
Serhiy Storchaka645058d2015-05-06 14:00:04 +0300909 return self.tk.getint(
Fredrik Lundh06d28152000-08-09 18:03:12 +0000910 self.tk.call('winfo', 'rooty', self._w))
911 def winfo_screen(self):
912 """Return the screen name of this widget."""
913 return self.tk.call('winfo', 'screen', self._w)
914 def winfo_screencells(self):
915 """Return the number of the cells in the colormap of the screen
916 of this widget."""
Serhiy Storchaka645058d2015-05-06 14:00:04 +0300917 return self.tk.getint(
Fredrik Lundh06d28152000-08-09 18:03:12 +0000918 self.tk.call('winfo', 'screencells', self._w))
919 def winfo_screendepth(self):
920 """Return the number of bits per pixel of the root window of the
921 screen of this widget."""
Serhiy Storchaka645058d2015-05-06 14:00:04 +0300922 return self.tk.getint(
Fredrik Lundh06d28152000-08-09 18:03:12 +0000923 self.tk.call('winfo', 'screendepth', self._w))
924 def winfo_screenheight(self):
925 """Return the number of pixels of the height of the screen of this widget
926 in pixel."""
Serhiy Storchaka645058d2015-05-06 14:00:04 +0300927 return self.tk.getint(
Fredrik Lundh06d28152000-08-09 18:03:12 +0000928 self.tk.call('winfo', 'screenheight', self._w))
929 def winfo_screenmmheight(self):
930 """Return the number of pixels of the height of the screen of
931 this widget in mm."""
Serhiy Storchaka645058d2015-05-06 14:00:04 +0300932 return self.tk.getint(
Fredrik Lundh06d28152000-08-09 18:03:12 +0000933 self.tk.call('winfo', 'screenmmheight', self._w))
934 def winfo_screenmmwidth(self):
935 """Return the number of pixels of the width of the screen of
936 this widget in mm."""
Serhiy Storchaka645058d2015-05-06 14:00:04 +0300937 return self.tk.getint(
Fredrik Lundh06d28152000-08-09 18:03:12 +0000938 self.tk.call('winfo', 'screenmmwidth', self._w))
939 def winfo_screenvisual(self):
940 """Return one of the strings directcolor, grayscale, pseudocolor,
941 staticcolor, staticgray, or truecolor for the default
942 colormodel of this screen."""
943 return self.tk.call('winfo', 'screenvisual', self._w)
944 def winfo_screenwidth(self):
945 """Return the number of pixels of the width of the screen of
946 this widget in pixel."""
Serhiy Storchaka645058d2015-05-06 14:00:04 +0300947 return self.tk.getint(
Fredrik Lundh06d28152000-08-09 18:03:12 +0000948 self.tk.call('winfo', 'screenwidth', self._w))
949 def winfo_server(self):
950 """Return information of the X-Server of the screen of this widget in
951 the form "XmajorRminor vendor vendorVersion"."""
952 return self.tk.call('winfo', 'server', self._w)
953 def winfo_toplevel(self):
954 """Return the toplevel widget of this widget."""
955 return self._nametowidget(self.tk.call(
956 'winfo', 'toplevel', self._w))
957 def winfo_viewable(self):
958 """Return true if the widget and all its higher ancestors are mapped."""
Serhiy Storchaka645058d2015-05-06 14:00:04 +0300959 return self.tk.getint(
Fredrik Lundh06d28152000-08-09 18:03:12 +0000960 self.tk.call('winfo', 'viewable', self._w))
961 def winfo_visual(self):
962 """Return one of the strings directcolor, grayscale, pseudocolor,
963 staticcolor, staticgray, or truecolor for the
964 colormodel of this widget."""
965 return self.tk.call('winfo', 'visual', self._w)
966 def winfo_visualid(self):
967 """Return the X identifier for the visual for this widget."""
968 return self.tk.call('winfo', 'visualid', self._w)
969 def winfo_visualsavailable(self, includeids=0):
970 """Return a list of all visuals available for the screen
971 of this widget.
Guido van Rossum5917ecb2000-06-29 16:30:50 +0000972
Fredrik Lundh06d28152000-08-09 18:03:12 +0000973 Each item in the list consists of a visual name (see winfo_visual), a
974 depth and if INCLUDEIDS=1 is given also the X identifier."""
975 data = self.tk.split(
976 self.tk.call('winfo', 'visualsavailable', self._w,
977 includeids and 'includeids' or None))
Guido van Rossum13257902007-06-07 23:15:56 +0000978 if isinstance(data, str):
Fredrik Lundh24037f72000-08-09 19:26:47 +0000979 data = [self.tk.split(data)]
Alexander Belopolsky022f0492010-11-22 19:40:51 +0000980 return [self.__winfo_parseitem(x) for x in data]
Fredrik Lundh06d28152000-08-09 18:03:12 +0000981 def __winfo_parseitem(self, t):
982 """Internal function."""
983 return t[:1] + tuple(map(self.__winfo_getint, t[1:]))
984 def __winfo_getint(self, x):
985 """Internal function."""
Eric S. Raymondfc170b12001-02-09 11:51:27 +0000986 return int(x, 0)
Fredrik Lundh06d28152000-08-09 18:03:12 +0000987 def winfo_vrootheight(self):
988 """Return the height of the virtual root window associated with this
989 widget in pixels. If there is no virtual root window return the
990 height of the screen."""
Serhiy Storchaka645058d2015-05-06 14:00:04 +0300991 return self.tk.getint(
Fredrik Lundh06d28152000-08-09 18:03:12 +0000992 self.tk.call('winfo', 'vrootheight', self._w))
993 def winfo_vrootwidth(self):
994 """Return the width of the virtual root window associated with this
995 widget in pixel. If there is no virtual root window return the
996 width of the screen."""
Serhiy Storchaka645058d2015-05-06 14:00:04 +0300997 return self.tk.getint(
Fredrik Lundh06d28152000-08-09 18:03:12 +0000998 self.tk.call('winfo', 'vrootwidth', self._w))
999 def winfo_vrootx(self):
1000 """Return the x offset of the virtual root relative to the root
1001 window of the screen of this widget."""
Serhiy Storchaka645058d2015-05-06 14:00:04 +03001002 return self.tk.getint(
Fredrik Lundh06d28152000-08-09 18:03:12 +00001003 self.tk.call('winfo', 'vrootx', self._w))
1004 def winfo_vrooty(self):
1005 """Return the y offset of the virtual root relative to the root
1006 window of the screen of this widget."""
Serhiy Storchaka645058d2015-05-06 14:00:04 +03001007 return self.tk.getint(
Fredrik Lundh06d28152000-08-09 18:03:12 +00001008 self.tk.call('winfo', 'vrooty', self._w))
1009 def winfo_width(self):
1010 """Return the width of this widget."""
Serhiy Storchaka645058d2015-05-06 14:00:04 +03001011 return self.tk.getint(
Fredrik Lundh06d28152000-08-09 18:03:12 +00001012 self.tk.call('winfo', 'width', self._w))
1013 def winfo_x(self):
1014 """Return the x coordinate of the upper left corner of this widget
1015 in the parent."""
Serhiy Storchaka645058d2015-05-06 14:00:04 +03001016 return self.tk.getint(
Fredrik Lundh06d28152000-08-09 18:03:12 +00001017 self.tk.call('winfo', 'x', self._w))
1018 def winfo_y(self):
1019 """Return the y coordinate of the upper left corner of this widget
1020 in the parent."""
Serhiy Storchaka645058d2015-05-06 14:00:04 +03001021 return self.tk.getint(
Fredrik Lundh06d28152000-08-09 18:03:12 +00001022 self.tk.call('winfo', 'y', self._w))
1023 def update(self):
1024 """Enter event loop until all pending events have been processed by Tcl."""
1025 self.tk.call('update')
1026 def update_idletasks(self):
1027 """Enter event loop until all idle callbacks have been called. This
1028 will update the display of windows but not process events caused by
1029 the user."""
1030 self.tk.call('update', 'idletasks')
1031 def bindtags(self, tagList=None):
1032 """Set or get the list of bindtags for this widget.
Guido van Rossum5917ecb2000-06-29 16:30:50 +00001033
Fredrik Lundh06d28152000-08-09 18:03:12 +00001034 With no argument return the list of all bindtags associated with
1035 this widget. With a list of strings as argument the bindtags are
1036 set to this list. The bindtags determine in which order events are
1037 processed (see bind)."""
1038 if tagList is None:
1039 return self.tk.splitlist(
1040 self.tk.call('bindtags', self._w))
1041 else:
1042 self.tk.call('bindtags', self._w, tagList)
1043 def _bind(self, what, sequence, func, add, needcleanup=1):
1044 """Internal function."""
Guido van Rossum13257902007-06-07 23:15:56 +00001045 if isinstance(func, str):
Fredrik Lundh06d28152000-08-09 18:03:12 +00001046 self.tk.call(what + (sequence, func))
1047 elif func:
1048 funcid = self._register(func, self._substitute,
1049 needcleanup)
1050 cmd = ('%sif {"[%s %s]" == "break"} break\n'
1051 %
1052 (add and '+' or '',
Martin v. Löwisc8718c12001-08-09 16:57:33 +00001053 funcid, self._subst_format_str))
Fredrik Lundh06d28152000-08-09 18:03:12 +00001054 self.tk.call(what + (sequence, cmd))
1055 return funcid
1056 elif sequence:
1057 return self.tk.call(what + (sequence,))
1058 else:
1059 return self.tk.splitlist(self.tk.call(what))
1060 def bind(self, sequence=None, func=None, add=None):
1061 """Bind to this widget at event SEQUENCE a call to function FUNC.
Guido van Rossum5917ecb2000-06-29 16:30:50 +00001062
Fredrik Lundh06d28152000-08-09 18:03:12 +00001063 SEQUENCE is a string of concatenated event
1064 patterns. An event pattern is of the form
1065 <MODIFIER-MODIFIER-TYPE-DETAIL> where MODIFIER is one
1066 of Control, Mod2, M2, Shift, Mod3, M3, Lock, Mod4, M4,
1067 Button1, B1, Mod5, M5 Button2, B2, Meta, M, Button3,
1068 B3, Alt, Button4, B4, Double, Button5, B5 Triple,
1069 Mod1, M1. TYPE is one of Activate, Enter, Map,
1070 ButtonPress, Button, Expose, Motion, ButtonRelease
1071 FocusIn, MouseWheel, Circulate, FocusOut, Property,
1072 Colormap, Gravity Reparent, Configure, KeyPress, Key,
1073 Unmap, Deactivate, KeyRelease Visibility, Destroy,
1074 Leave and DETAIL is the button number for ButtonPress,
1075 ButtonRelease and DETAIL is the Keysym for KeyPress and
1076 KeyRelease. Examples are
1077 <Control-Button-1> for pressing Control and mouse button 1 or
1078 <Alt-A> for pressing A and the Alt key (KeyPress can be omitted).
1079 An event pattern can also be a virtual event of the form
1080 <<AString>> where AString can be arbitrary. This
1081 event can be generated by event_generate.
1082 If events are concatenated they must appear shortly
1083 after each other.
Guido van Rossum5917ecb2000-06-29 16:30:50 +00001084
Fredrik Lundh06d28152000-08-09 18:03:12 +00001085 FUNC will be called if the event sequence occurs with an
1086 instance of Event as argument. If the return value of FUNC is
1087 "break" no further bound function is invoked.
Guido van Rossum5917ecb2000-06-29 16:30:50 +00001088
Fredrik Lundh06d28152000-08-09 18:03:12 +00001089 An additional boolean parameter ADD specifies whether FUNC will
1090 be called additionally to the other bound function or whether
1091 it will replace the previous function.
Guido van Rossum5917ecb2000-06-29 16:30:50 +00001092
Fredrik Lundh06d28152000-08-09 18:03:12 +00001093 Bind will return an identifier to allow deletion of the bound function with
1094 unbind without memory leak.
Guido van Rossum5917ecb2000-06-29 16:30:50 +00001095
Fredrik Lundh06d28152000-08-09 18:03:12 +00001096 If FUNC or SEQUENCE is omitted the bound function or list
1097 of bound events are returned."""
Guido van Rossum5917ecb2000-06-29 16:30:50 +00001098
Fredrik Lundh06d28152000-08-09 18:03:12 +00001099 return self._bind(('bind', self._w), sequence, func, add)
1100 def unbind(self, sequence, funcid=None):
1101 """Unbind for this widget for event SEQUENCE the
1102 function identified with FUNCID."""
1103 self.tk.call('bind', self._w, sequence, '')
1104 if funcid:
1105 self.deletecommand(funcid)
1106 def bind_all(self, sequence=None, func=None, add=None):
1107 """Bind to all widgets at an event SEQUENCE a call to function FUNC.
1108 An additional boolean parameter ADD specifies whether FUNC will
1109 be called additionally to the other bound function or whether
1110 it will replace the previous function. See bind for the return value."""
1111 return self._bind(('bind', 'all'), sequence, func, add, 0)
1112 def unbind_all(self, sequence):
1113 """Unbind for all widgets for event SEQUENCE all functions."""
1114 self.tk.call('bind', 'all' , sequence, '')
1115 def bind_class(self, className, sequence=None, func=None, add=None):
Guido van Rossum5917ecb2000-06-29 16:30:50 +00001116
Fredrik Lundh06d28152000-08-09 18:03:12 +00001117 """Bind to widgets with bindtag CLASSNAME at event
1118 SEQUENCE a call of function FUNC. An additional
1119 boolean parameter ADD specifies whether FUNC will be
1120 called additionally to the other bound function or
1121 whether it will replace the previous function. See bind for
1122 the return value."""
Guido van Rossum5917ecb2000-06-29 16:30:50 +00001123
Fredrik Lundh06d28152000-08-09 18:03:12 +00001124 return self._bind(('bind', className), sequence, func, add, 0)
1125 def unbind_class(self, className, sequence):
Serhiy Storchakad65c9492015-11-02 14:10:23 +02001126 """Unbind for all widgets with bindtag CLASSNAME for event SEQUENCE
Fredrik Lundh06d28152000-08-09 18:03:12 +00001127 all functions."""
1128 self.tk.call('bind', className , sequence, '')
1129 def mainloop(self, n=0):
1130 """Call the mainloop of Tk."""
1131 self.tk.mainloop(n)
1132 def quit(self):
1133 """Quit the Tcl interpreter. All widgets will be destroyed."""
1134 self.tk.quit()
1135 def _getints(self, string):
1136 """Internal function."""
1137 if string:
Serhiy Storchaka645058d2015-05-06 14:00:04 +03001138 return tuple(map(self.tk.getint, self.tk.splitlist(string)))
Fredrik Lundh06d28152000-08-09 18:03:12 +00001139 def _getdoubles(self, string):
1140 """Internal function."""
1141 if string:
Serhiy Storchaka645058d2015-05-06 14:00:04 +03001142 return tuple(map(self.tk.getdouble, self.tk.splitlist(string)))
Fredrik Lundh06d28152000-08-09 18:03:12 +00001143 def _getboolean(self, string):
1144 """Internal function."""
1145 if string:
1146 return self.tk.getboolean(string)
1147 def _displayof(self, displayof):
1148 """Internal function."""
1149 if displayof:
1150 return ('-displayof', displayof)
1151 if displayof is None:
1152 return ('-displayof', self._w)
1153 return ()
Ned Deily4d377d92012-05-15 18:08:11 -07001154 @property
1155 def _windowingsystem(self):
1156 """Internal function."""
1157 try:
1158 return self._root()._windowingsystem_cached
1159 except AttributeError:
1160 ws = self._root()._windowingsystem_cached = \
1161 self.tk.call('tk', 'windowingsystem')
1162 return ws
Fredrik Lundh06d28152000-08-09 18:03:12 +00001163 def _options(self, cnf, kw = None):
1164 """Internal function."""
1165 if kw:
1166 cnf = _cnfmerge((cnf, kw))
1167 else:
1168 cnf = _cnfmerge(cnf)
1169 res = ()
1170 for k, v in cnf.items():
1171 if v is not None:
1172 if k[-1] == '_': k = k[:-1]
Florent Xicluna5d1155c2011-10-28 14:45:05 +02001173 if callable(v):
Fredrik Lundh06d28152000-08-09 18:03:12 +00001174 v = self._register(v)
Georg Brandlbf1eb632008-05-29 07:19:00 +00001175 elif isinstance(v, (tuple, list)):
Georg Brandl3b550032008-06-03 10:25:47 +00001176 nv = []
Georg Brandlbf1eb632008-05-29 07:19:00 +00001177 for item in v:
Georg Brandl3b550032008-06-03 10:25:47 +00001178 if isinstance(item, int):
1179 nv.append(str(item))
1180 elif isinstance(item, str):
Serhiy Storchakab1396522013-01-15 17:56:08 +02001181 nv.append(_stringify(item))
Georg Brandl3b550032008-06-03 10:25:47 +00001182 else:
Georg Brandlbf1eb632008-05-29 07:19:00 +00001183 break
1184 else:
Georg Brandl3b550032008-06-03 10:25:47 +00001185 v = ' '.join(nv)
Fredrik Lundh06d28152000-08-09 18:03:12 +00001186 res = res + ('-'+k, v)
1187 return res
1188 def nametowidget(self, name):
1189 """Return the Tkinter instance of a widget identified by
1190 its Tcl name NAME."""
Martin v. Löwiscdfae162008-08-02 07:23:15 +00001191 name = str(name).split('.')
Fredrik Lundh06d28152000-08-09 18:03:12 +00001192 w = self
Martin v. Löwiscdfae162008-08-02 07:23:15 +00001193
1194 if not name[0]:
Fredrik Lundh06d28152000-08-09 18:03:12 +00001195 w = w._root()
1196 name = name[1:]
Martin v. Löwiscdfae162008-08-02 07:23:15 +00001197
1198 for n in name:
1199 if not n:
1200 break
1201 w = w.children[n]
1202
Fredrik Lundh06d28152000-08-09 18:03:12 +00001203 return w
1204 _nametowidget = nametowidget
1205 def _register(self, func, subst=None, needcleanup=1):
1206 """Return a newly created Tcl function. If this
1207 function is called, the Python function FUNC will
1208 be executed. An optional function SUBST can
1209 be given which will be executed before FUNC."""
1210 f = CallWrapper(func, subst, self).__call__
Walter Dörwald70a6b492004-02-12 17:35:32 +00001211 name = repr(id(f))
Fredrik Lundh06d28152000-08-09 18:03:12 +00001212 try:
Christian Heimesff737952007-11-27 10:40:20 +00001213 func = func.__func__
Fredrik Lundh06d28152000-08-09 18:03:12 +00001214 except AttributeError:
1215 pass
1216 try:
1217 name = name + func.__name__
1218 except AttributeError:
1219 pass
1220 self.tk.createcommand(name, f)
1221 if needcleanup:
1222 if self._tclCommands is None:
1223 self._tclCommands = []
1224 self._tclCommands.append(name)
Fredrik Lundh06d28152000-08-09 18:03:12 +00001225 return name
1226 register = _register
1227 def _root(self):
1228 """Internal function."""
1229 w = self
1230 while w.master: w = w.master
1231 return w
1232 _subst_format = ('%#', '%b', '%f', '%h', '%k',
1233 '%s', '%t', '%w', '%x', '%y',
1234 '%A', '%E', '%K', '%N', '%W', '%T', '%X', '%Y', '%D')
Martin v. Löwisc8718c12001-08-09 16:57:33 +00001235 _subst_format_str = " ".join(_subst_format)
Fredrik Lundh06d28152000-08-09 18:03:12 +00001236 def _substitute(self, *args):
1237 """Internal function."""
1238 if len(args) != len(self._subst_format): return args
1239 getboolean = self.tk.getboolean
Martin v. Löwis043bbc72003-03-29 09:47:21 +00001240
Serhiy Storchaka645058d2015-05-06 14:00:04 +03001241 getint = self.tk.getint
Martin v. Löwis043bbc72003-03-29 09:47:21 +00001242 def getint_event(s):
1243 """Tk changed behavior in 8.4.2, returning "??" rather more often."""
1244 try:
Serhiy Storchaka645058d2015-05-06 14:00:04 +03001245 return getint(s)
1246 except (ValueError, TclError):
Martin v. Löwis043bbc72003-03-29 09:47:21 +00001247 return s
1248
Fredrik Lundh06d28152000-08-09 18:03:12 +00001249 nsign, b, f, h, k, s, t, w, x, y, A, E, K, N, W, T, X, Y, D = args
1250 # Missing: (a, c, d, m, o, v, B, R)
1251 e = Event()
Martin v. Löwis043bbc72003-03-29 09:47:21 +00001252 # serial field: valid vor all events
1253 # number of button: ButtonPress and ButtonRelease events only
1254 # height field: Configure, ConfigureRequest, Create,
1255 # ResizeRequest, and Expose events only
1256 # keycode field: KeyPress and KeyRelease events only
1257 # time field: "valid for events that contain a time field"
1258 # width field: Configure, ConfigureRequest, Create, ResizeRequest,
1259 # and Expose events only
1260 # x field: "valid for events that contain a x field"
1261 # y field: "valid for events that contain a y field"
1262 # keysym as decimal: KeyPress and KeyRelease events only
1263 # x_root, y_root fields: ButtonPress, ButtonRelease, KeyPress,
1264 # KeyRelease,and Motion events
Fredrik Lundh06d28152000-08-09 18:03:12 +00001265 e.serial = getint(nsign)
Martin v. Löwis043bbc72003-03-29 09:47:21 +00001266 e.num = getint_event(b)
Fredrik Lundh06d28152000-08-09 18:03:12 +00001267 try: e.focus = getboolean(f)
1268 except TclError: pass
Martin v. Löwis043bbc72003-03-29 09:47:21 +00001269 e.height = getint_event(h)
1270 e.keycode = getint_event(k)
1271 e.state = getint_event(s)
1272 e.time = getint_event(t)
1273 e.width = getint_event(w)
1274 e.x = getint_event(x)
1275 e.y = getint_event(y)
Fredrik Lundh06d28152000-08-09 18:03:12 +00001276 e.char = A
1277 try: e.send_event = getboolean(E)
1278 except TclError: pass
1279 e.keysym = K
Martin v. Löwis043bbc72003-03-29 09:47:21 +00001280 e.keysym_num = getint_event(N)
Fredrik Lundh06d28152000-08-09 18:03:12 +00001281 e.type = T
1282 try:
1283 e.widget = self._nametowidget(W)
1284 except KeyError:
1285 e.widget = W
Martin v. Löwis043bbc72003-03-29 09:47:21 +00001286 e.x_root = getint_event(X)
1287 e.y_root = getint_event(Y)
Fredrik Lundha249f162000-09-07 15:05:09 +00001288 try:
1289 e.delta = getint(D)
Serhiy Storchaka645058d2015-05-06 14:00:04 +03001290 except (ValueError, TclError):
Fredrik Lundha249f162000-09-07 15:05:09 +00001291 e.delta = 0
Fredrik Lundh06d28152000-08-09 18:03:12 +00001292 return (e,)
1293 def _report_exception(self):
1294 """Internal function."""
Neal Norwitzac3625f2006-03-17 05:49:33 +00001295 exc, val, tb = sys.exc_info()
Fredrik Lundh06d28152000-08-09 18:03:12 +00001296 root = self._root()
1297 root.report_callback_exception(exc, val, tb)
Serhiy Storchaka848972c2013-12-25 16:35:38 +02001298
1299 def _getconfigure(self, *args):
1300 """Call Tcl configure command and return the result as a dict."""
1301 cnf = {}
1302 for x in self.tk.splitlist(self.tk.call(*args)):
1303 x = self.tk.splitlist(x)
1304 cnf[x[0][1:]] = (x[0][1:],) + x[1:]
1305 return cnf
1306
1307 def _getconfigure1(self, *args):
1308 x = self.tk.splitlist(self.tk.call(*args))
1309 return (x[0][1:],) + x[1:]
1310
Martin v. Löwis6ce13152002-10-10 14:36:13 +00001311 def _configure(self, cmd, cnf, kw):
1312 """Internal function."""
1313 if kw:
1314 cnf = _cnfmerge((cnf, kw))
1315 elif cnf:
1316 cnf = _cnfmerge(cnf)
1317 if cnf is None:
Serhiy Storchaka848972c2013-12-25 16:35:38 +02001318 return self._getconfigure(_flatten((self._w, cmd)))
Guido van Rossum13257902007-06-07 23:15:56 +00001319 if isinstance(cnf, str):
Serhiy Storchaka848972c2013-12-25 16:35:38 +02001320 return self._getconfigure1(_flatten((self._w, cmd, '-'+cnf)))
Martin v. Löwis6ce13152002-10-10 14:36:13 +00001321 self.tk.call(_flatten((self._w, cmd)) + self._options(cnf))
Fredrik Lundh06d28152000-08-09 18:03:12 +00001322 # These used to be defined in Widget:
1323 def configure(self, cnf=None, **kw):
1324 """Configure resources of a widget.
Barry Warsaw107e6231998-12-15 00:44:15 +00001325
Fredrik Lundh06d28152000-08-09 18:03:12 +00001326 The values for resources are specified as keyword
1327 arguments. To get an overview about
1328 the allowed keyword arguments call the method keys.
1329 """
Martin v. Löwis6ce13152002-10-10 14:36:13 +00001330 return self._configure('configure', cnf, kw)
Fredrik Lundh06d28152000-08-09 18:03:12 +00001331 config = configure
1332 def cget(self, key):
1333 """Return the resource value for a KEY given as string."""
1334 return self.tk.call(self._w, 'cget', '-' + key)
1335 __getitem__ = cget
1336 def __setitem__(self, key, value):
1337 self.configure({key: value})
1338 def keys(self):
1339 """Return a list of all resource names of this widget."""
Serhiy Storchaka42a43662016-03-09 10:33:51 +02001340 splitlist = self.tk.splitlist
1341 return [splitlist(x)[0][1:] for x in
1342 splitlist(self.tk.call(self._w, 'configure'))]
Fredrik Lundh06d28152000-08-09 18:03:12 +00001343 def __str__(self):
1344 """Return the window path name of this widget."""
1345 return self._w
Serhiy Storchakabcc17462014-04-04 15:45:02 +03001346
1347 def __repr__(self):
1348 return '<%s.%s object %s>' % (
1349 self.__class__.__module__, self.__class__.__qualname__, self._w)
1350
Fredrik Lundh06d28152000-08-09 18:03:12 +00001351 # Pack methods that apply to the master
1352 _noarg_ = ['_noarg_']
1353 def pack_propagate(self, flag=_noarg_):
1354 """Set or get the status for propagation of geometry information.
Guido van Rossum5917ecb2000-06-29 16:30:50 +00001355
Fredrik Lundh06d28152000-08-09 18:03:12 +00001356 A boolean argument specifies whether the geometry information
1357 of the slaves will determine the size of this widget. If no argument
1358 is given the current setting will be returned.
1359 """
1360 if flag is Misc._noarg_:
1361 return self._getboolean(self.tk.call(
1362 'pack', 'propagate', self._w))
1363 else:
1364 self.tk.call('pack', 'propagate', self._w, flag)
1365 propagate = pack_propagate
1366 def pack_slaves(self):
1367 """Return a list of all slaves of this widget
1368 in its packing order."""
Alexander Belopolsky022f0492010-11-22 19:40:51 +00001369 return [self._nametowidget(x) for x in
1370 self.tk.splitlist(
1371 self.tk.call('pack', 'slaves', self._w))]
Fredrik Lundh06d28152000-08-09 18:03:12 +00001372 slaves = pack_slaves
1373 # Place method that applies to the master
1374 def place_slaves(self):
1375 """Return a list of all slaves of this widget
1376 in its packing order."""
Alexander Belopolsky022f0492010-11-22 19:40:51 +00001377 return [self._nametowidget(x) for x in
1378 self.tk.splitlist(
Fredrik Lundh06d28152000-08-09 18:03:12 +00001379 self.tk.call(
Alexander Belopolsky022f0492010-11-22 19:40:51 +00001380 'place', 'slaves', self._w))]
Fredrik Lundh06d28152000-08-09 18:03:12 +00001381 # Grid methods that apply to the master
Martin v. Löwis5c3c4242012-03-13 13:40:42 -07001382 def grid_anchor(self, anchor=None): # new in Tk 8.5
1383 """The anchor value controls how to place the grid within the
1384 master when no row/column has any weight.
1385
1386 The default anchor is nw."""
1387 self.tk.call('grid', 'anchor', self._w, anchor)
1388 anchor = grid_anchor
Fredrik Lundh06d28152000-08-09 18:03:12 +00001389 def grid_bbox(self, column=None, row=None, col2=None, row2=None):
1390 """Return a tuple of integer coordinates for the bounding
1391 box of this widget controlled by the geometry manager grid.
Guido van Rossum5917ecb2000-06-29 16:30:50 +00001392
Fredrik Lundh06d28152000-08-09 18:03:12 +00001393 If COLUMN, ROW is given the bounding box applies from
1394 the cell with row and column 0 to the specified
1395 cell. If COL2 and ROW2 are given the bounding box
1396 starts at that cell.
Guido van Rossum5917ecb2000-06-29 16:30:50 +00001397
Fredrik Lundh06d28152000-08-09 18:03:12 +00001398 The returned integers specify the offset of the upper left
1399 corner in the master widget and the width and height.
1400 """
1401 args = ('grid', 'bbox', self._w)
1402 if column is not None and row is not None:
1403 args = args + (column, row)
1404 if col2 is not None and row2 is not None:
1405 args = args + (col2, row2)
Raymond Hettingerff41c482003-04-06 09:01:11 +00001406 return self._getints(self.tk.call(*args)) or None
Fredrik Lundh06d28152000-08-09 18:03:12 +00001407 bbox = grid_bbox
Serhiy Storchakae9597762014-02-19 18:34:05 +02001408
1409 def _gridconvvalue(self, value):
1410 if isinstance(value, (str, _tkinter.Tcl_Obj)):
1411 try:
1412 svalue = str(value)
1413 if not svalue:
1414 return None
1415 elif '.' in svalue:
Serhiy Storchaka645058d2015-05-06 14:00:04 +03001416 return self.tk.getdouble(svalue)
Serhiy Storchakae9597762014-02-19 18:34:05 +02001417 else:
Serhiy Storchaka645058d2015-05-06 14:00:04 +03001418 return self.tk.getint(svalue)
1419 except (ValueError, TclError):
Serhiy Storchakae9597762014-02-19 18:34:05 +02001420 pass
1421 return value
1422
Fredrik Lundh06d28152000-08-09 18:03:12 +00001423 def _grid_configure(self, command, index, cnf, kw):
1424 """Internal function."""
Guido van Rossum13257902007-06-07 23:15:56 +00001425 if isinstance(cnf, str) and not kw:
Fredrik Lundh06d28152000-08-09 18:03:12 +00001426 if cnf[-1:] == '_':
1427 cnf = cnf[:-1]
1428 if cnf[:1] != '-':
1429 cnf = '-'+cnf
1430 options = (cnf,)
1431 else:
1432 options = self._options(cnf, kw)
1433 if not options:
Serhiy Storchaka8f0a1d02014-09-06 22:47:58 +03001434 return _splitdict(
1435 self.tk,
1436 self.tk.call('grid', command, self._w, index),
1437 conv=self._gridconvvalue)
Fredrik Lundh06d28152000-08-09 18:03:12 +00001438 res = self.tk.call(
1439 ('grid', command, self._w, index)
1440 + options)
1441 if len(options) == 1:
Serhiy Storchakae9597762014-02-19 18:34:05 +02001442 return self._gridconvvalue(res)
1443
Fredrik Lundh06d28152000-08-09 18:03:12 +00001444 def grid_columnconfigure(self, index, cnf={}, **kw):
1445 """Configure column INDEX of a grid.
Guido van Rossum80f8be81997-12-02 19:51:39 +00001446
Fredrik Lundh06d28152000-08-09 18:03:12 +00001447 Valid resources are minsize (minimum size of the column),
1448 weight (how much does additional space propagate to this column)
1449 and pad (how much space to let additionally)."""
1450 return self._grid_configure('columnconfigure', index, cnf, kw)
1451 columnconfigure = grid_columnconfigure
Martin v. Löwisdc579092001-10-13 09:33:51 +00001452 def grid_location(self, x, y):
1453 """Return a tuple of column and row which identify the cell
1454 at which the pixel at position X and Y inside the master
1455 widget is located."""
1456 return self._getints(
1457 self.tk.call(
1458 'grid', 'location', self._w, x, y)) or None
Fredrik Lundh06d28152000-08-09 18:03:12 +00001459 def grid_propagate(self, flag=_noarg_):
1460 """Set or get the status for propagation of geometry information.
Guido van Rossum80f8be81997-12-02 19:51:39 +00001461
Fredrik Lundh06d28152000-08-09 18:03:12 +00001462 A boolean argument specifies whether the geometry information
1463 of the slaves will determine the size of this widget. If no argument
1464 is given, the current setting will be returned.
1465 """
1466 if flag is Misc._noarg_:
1467 return self._getboolean(self.tk.call(
1468 'grid', 'propagate', self._w))
1469 else:
1470 self.tk.call('grid', 'propagate', self._w, flag)
1471 def grid_rowconfigure(self, index, cnf={}, **kw):
1472 """Configure row INDEX of a grid.
Guido van Rossum80f8be81997-12-02 19:51:39 +00001473
Fredrik Lundh06d28152000-08-09 18:03:12 +00001474 Valid resources are minsize (minimum size of the row),
1475 weight (how much does additional space propagate to this row)
1476 and pad (how much space to let additionally)."""
1477 return self._grid_configure('rowconfigure', index, cnf, kw)
1478 rowconfigure = grid_rowconfigure
1479 def grid_size(self):
1480 """Return a tuple of the number of column and rows in the grid."""
1481 return self._getints(
1482 self.tk.call('grid', 'size', self._w)) or None
1483 size = grid_size
1484 def grid_slaves(self, row=None, column=None):
1485 """Return a list of all slaves of this widget
1486 in its packing order."""
1487 args = ()
1488 if row is not None:
1489 args = args + ('-row', row)
1490 if column is not None:
1491 args = args + ('-column', column)
Alexander Belopolsky022f0492010-11-22 19:40:51 +00001492 return [self._nametowidget(x) for x in
1493 self.tk.splitlist(self.tk.call(
1494 ('grid', 'slaves', self._w) + args))]
Guido van Rossum80f8be81997-12-02 19:51:39 +00001495
Fredrik Lundh06d28152000-08-09 18:03:12 +00001496 # Support for the "event" command, new in Tk 4.2.
1497 # By Case Roole.
Guido van Rossum80f8be81997-12-02 19:51:39 +00001498
Fredrik Lundh06d28152000-08-09 18:03:12 +00001499 def event_add(self, virtual, *sequences):
1500 """Bind a virtual event VIRTUAL (of the form <<Name>>)
1501 to an event SEQUENCE such that the virtual event is triggered
1502 whenever SEQUENCE occurs."""
1503 args = ('event', 'add', virtual) + sequences
1504 self.tk.call(args)
Guido van Rossumc2966511998-04-10 19:16:10 +00001505
Fredrik Lundh06d28152000-08-09 18:03:12 +00001506 def event_delete(self, virtual, *sequences):
1507 """Unbind a virtual event VIRTUAL from SEQUENCE."""
1508 args = ('event', 'delete', virtual) + sequences
1509 self.tk.call(args)
Guido van Rossumc2966511998-04-10 19:16:10 +00001510
Fredrik Lundh06d28152000-08-09 18:03:12 +00001511 def event_generate(self, sequence, **kw):
1512 """Generate an event SEQUENCE. Additional
1513 keyword arguments specify parameter of the event
1514 (e.g. x, y, rootx, rooty)."""
1515 args = ('event', 'generate', self._w, sequence)
1516 for k, v in kw.items():
1517 args = args + ('-%s' % k, str(v))
1518 self.tk.call(args)
1519
1520 def event_info(self, virtual=None):
1521 """Return a list of all virtual events or the information
1522 about the SEQUENCE bound to the virtual event VIRTUAL."""
1523 return self.tk.splitlist(
1524 self.tk.call('event', 'info', virtual))
1525
1526 # Image related commands
1527
1528 def image_names(self):
1529 """Return a list of all existing image names."""
Serhiy Storchakaa21acb52014-01-07 19:27:42 +02001530 return self.tk.splitlist(self.tk.call('image', 'names'))
Fredrik Lundh06d28152000-08-09 18:03:12 +00001531
1532 def image_types(self):
1533 """Return a list of all available image types (e.g. phote bitmap)."""
Serhiy Storchakaa21acb52014-01-07 19:27:42 +02001534 return self.tk.splitlist(self.tk.call('image', 'types'))
Guido van Rossumc2966511998-04-10 19:16:10 +00001535
Guido van Rossum80f8be81997-12-02 19:51:39 +00001536
Guido van Rossuma5773dd1995-09-07 19:22:00 +00001537class CallWrapper:
Fredrik Lundh06d28152000-08-09 18:03:12 +00001538 """Internal class. Stores function to call when some user
1539 defined Tcl function is called e.g. after an event occurred."""
1540 def __init__(self, func, subst, widget):
1541 """Store FUNC, SUBST and WIDGET as members."""
1542 self.func = func
1543 self.subst = subst
1544 self.widget = widget
1545 def __call__(self, *args):
1546 """Apply first function SUBST to arguments, than FUNC."""
1547 try:
1548 if self.subst:
Raymond Hettingerff41c482003-04-06 09:01:11 +00001549 args = self.subst(*args)
1550 return self.func(*args)
Andrew Svetloveb0abce2012-12-03 16:13:07 +02001551 except SystemExit:
1552 raise
Fredrik Lundh06d28152000-08-09 18:03:12 +00001553 except:
1554 self.widget._report_exception()
Guido van Rossum18468821994-06-20 07:49:28 +00001555
Guido van Rossume365a591998-05-01 19:48:20 +00001556
Guilherme Polo1fff0082009-08-14 15:05:30 +00001557class XView:
1558 """Mix-in class for querying and changing the horizontal position
1559 of a widget's window."""
1560
1561 def xview(self, *args):
1562 """Query and change the horizontal position of the view."""
1563 res = self.tk.call(self._w, 'xview', *args)
1564 if not args:
1565 return self._getdoubles(res)
1566
1567 def xview_moveto(self, fraction):
1568 """Adjusts the view in the window so that FRACTION of the
1569 total width of the canvas is off-screen to the left."""
1570 self.tk.call(self._w, 'xview', 'moveto', fraction)
1571
1572 def xview_scroll(self, number, what):
1573 """Shift the x-view according to NUMBER which is measured in "units"
1574 or "pages" (WHAT)."""
1575 self.tk.call(self._w, 'xview', 'scroll', number, what)
1576
1577
1578class YView:
1579 """Mix-in class for querying and changing the vertical position
1580 of a widget's window."""
1581
1582 def yview(self, *args):
1583 """Query and change the vertical position of the view."""
1584 res = self.tk.call(self._w, 'yview', *args)
1585 if not args:
1586 return self._getdoubles(res)
1587
1588 def yview_moveto(self, fraction):
1589 """Adjusts the view in the window so that FRACTION of the
1590 total height of the canvas is off-screen to the top."""
1591 self.tk.call(self._w, 'yview', 'moveto', fraction)
1592
1593 def yview_scroll(self, number, what):
1594 """Shift the y-view according to NUMBER which is measured in
1595 "units" or "pages" (WHAT)."""
1596 self.tk.call(self._w, 'yview', 'scroll', number, what)
1597
1598
Guido van Rossum18468821994-06-20 07:49:28 +00001599class Wm:
Fredrik Lundh06d28152000-08-09 18:03:12 +00001600 """Provides functions for the communication with the window manager."""
Raymond Hettingerff41c482003-04-06 09:01:11 +00001601
Fredrik Lundh06d28152000-08-09 18:03:12 +00001602 def wm_aspect(self,
1603 minNumer=None, minDenom=None,
1604 maxNumer=None, maxDenom=None):
1605 """Instruct the window manager to set the aspect ratio (width/height)
1606 of this widget to be between MINNUMER/MINDENOM and MAXNUMER/MAXDENOM. Return a tuple
1607 of the actual values if no argument is given."""
1608 return self._getints(
1609 self.tk.call('wm', 'aspect', self._w,
1610 minNumer, minDenom,
1611 maxNumer, maxDenom))
1612 aspect = wm_aspect
Raymond Hettingerff41c482003-04-06 09:01:11 +00001613
Martin v. Löwis2ec36272002-10-13 10:22:08 +00001614 def wm_attributes(self, *args):
1615 """This subcommand returns or sets platform specific attributes
Raymond Hettingerff41c482003-04-06 09:01:11 +00001616
1617 The first form returns a list of the platform specific flags and
1618 their values. The second form returns the value for the specific
Martin v. Löwis2ec36272002-10-13 10:22:08 +00001619 option. The third form sets one or more of the values. The values
1620 are as follows:
Raymond Hettingerff41c482003-04-06 09:01:11 +00001621
1622 On Windows, -disabled gets or sets whether the window is in a
Martin v. Löwis2ec36272002-10-13 10:22:08 +00001623 disabled state. -toolwindow gets or sets the style of the window
Raymond Hettingerff41c482003-04-06 09:01:11 +00001624 to toolwindow (as defined in the MSDN). -topmost gets or sets
1625 whether this is a topmost window (displays above all other
Martin v. Löwis2ec36272002-10-13 10:22:08 +00001626 windows).
Raymond Hettingerff41c482003-04-06 09:01:11 +00001627
1628 On Macintosh, XXXXX
1629
Martin v. Löwis2ec36272002-10-13 10:22:08 +00001630 On Unix, there are currently no special attribute values.
1631 """
1632 args = ('wm', 'attributes', self._w) + args
1633 return self.tk.call(args)
1634 attributes=wm_attributes
Raymond Hettingerff41c482003-04-06 09:01:11 +00001635
Fredrik Lundh06d28152000-08-09 18:03:12 +00001636 def wm_client(self, name=None):
1637 """Store NAME in WM_CLIENT_MACHINE property of this widget. Return
1638 current value."""
1639 return self.tk.call('wm', 'client', self._w, name)
1640 client = wm_client
1641 def wm_colormapwindows(self, *wlist):
1642 """Store list of window names (WLIST) into WM_COLORMAPWINDOWS property
1643 of this widget. This list contains windows whose colormaps differ from their
1644 parents. Return current list of widgets if WLIST is empty."""
1645 if len(wlist) > 1:
1646 wlist = (wlist,) # Tk needs a list of windows here
1647 args = ('wm', 'colormapwindows', self._w) + wlist
Serhiy Storchakaa21acb52014-01-07 19:27:42 +02001648 if wlist:
1649 self.tk.call(args)
1650 else:
1651 return [self._nametowidget(x)
1652 for x in self.tk.splitlist(self.tk.call(args))]
Fredrik Lundh06d28152000-08-09 18:03:12 +00001653 colormapwindows = wm_colormapwindows
1654 def wm_command(self, value=None):
1655 """Store VALUE in WM_COMMAND property. It is the command
1656 which shall be used to invoke the application. Return current
1657 command if VALUE is None."""
1658 return self.tk.call('wm', 'command', self._w, value)
1659 command = wm_command
1660 def wm_deiconify(self):
1661 """Deiconify this widget. If it was never mapped it will not be mapped.
1662 On Windows it will raise this widget and give it the focus."""
1663 return self.tk.call('wm', 'deiconify', self._w)
1664 deiconify = wm_deiconify
1665 def wm_focusmodel(self, model=None):
1666 """Set focus model to MODEL. "active" means that this widget will claim
1667 the focus itself, "passive" means that the window manager shall give
1668 the focus. Return current focus model if MODEL is None."""
1669 return self.tk.call('wm', 'focusmodel', self._w, model)
1670 focusmodel = wm_focusmodel
Martin v. Löwis5c3c4242012-03-13 13:40:42 -07001671 def wm_forget(self, window): # new in Tk 8.5
1672 """The window will be unmappend from the screen and will no longer
1673 be managed by wm. toplevel windows will be treated like frame
1674 windows once they are no longer managed by wm, however, the menu
1675 option configuration will be remembered and the menus will return
1676 once the widget is managed again."""
1677 self.tk.call('wm', 'forget', window)
1678 forget = wm_forget
Fredrik Lundh06d28152000-08-09 18:03:12 +00001679 def wm_frame(self):
1680 """Return identifier for decorative frame of this widget if present."""
1681 return self.tk.call('wm', 'frame', self._w)
1682 frame = wm_frame
1683 def wm_geometry(self, newGeometry=None):
1684 """Set geometry to NEWGEOMETRY of the form =widthxheight+x+y. Return
1685 current value if None is given."""
1686 return self.tk.call('wm', 'geometry', self._w, newGeometry)
1687 geometry = wm_geometry
1688 def wm_grid(self,
1689 baseWidth=None, baseHeight=None,
1690 widthInc=None, heightInc=None):
1691 """Instruct the window manager that this widget shall only be
1692 resized on grid boundaries. WIDTHINC and HEIGHTINC are the width and
1693 height of a grid unit in pixels. BASEWIDTH and BASEHEIGHT are the
1694 number of grid units requested in Tk_GeometryRequest."""
1695 return self._getints(self.tk.call(
1696 'wm', 'grid', self._w,
1697 baseWidth, baseHeight, widthInc, heightInc))
1698 grid = wm_grid
1699 def wm_group(self, pathName=None):
1700 """Set the group leader widgets for related widgets to PATHNAME. Return
1701 the group leader of this widget if None is given."""
1702 return self.tk.call('wm', 'group', self._w, pathName)
1703 group = wm_group
Thomas Wouters0e3f5912006-08-11 14:57:12 +00001704 def wm_iconbitmap(self, bitmap=None, default=None):
Fredrik Lundh06d28152000-08-09 18:03:12 +00001705 """Set bitmap for the iconified widget to BITMAP. Return
Thomas Wouters0e3f5912006-08-11 14:57:12 +00001706 the bitmap if None is given.
1707
1708 Under Windows, the DEFAULT parameter can be used to set the icon
1709 for the widget and any descendents that don't have an icon set
1710 explicitly. DEFAULT can be the relative path to a .ico file
1711 (example: root.iconbitmap(default='myicon.ico') ). See Tk
1712 documentation for more information."""
1713 if default:
1714 return self.tk.call('wm', 'iconbitmap', self._w, '-default', default)
1715 else:
1716 return self.tk.call('wm', 'iconbitmap', self._w, bitmap)
Fredrik Lundh06d28152000-08-09 18:03:12 +00001717 iconbitmap = wm_iconbitmap
1718 def wm_iconify(self):
1719 """Display widget as icon."""
1720 return self.tk.call('wm', 'iconify', self._w)
1721 iconify = wm_iconify
1722 def wm_iconmask(self, bitmap=None):
1723 """Set mask for the icon bitmap of this widget. Return the
1724 mask if None is given."""
1725 return self.tk.call('wm', 'iconmask', self._w, bitmap)
1726 iconmask = wm_iconmask
1727 def wm_iconname(self, newName=None):
1728 """Set the name of the icon for this widget. Return the name if
1729 None is given."""
1730 return self.tk.call('wm', 'iconname', self._w, newName)
1731 iconname = wm_iconname
Martin v. Löwis5c3c4242012-03-13 13:40:42 -07001732 def wm_iconphoto(self, default=False, *args): # new in Tk 8.5
1733 """Sets the titlebar icon for this window based on the named photo
1734 images passed through args. If default is True, this is applied to
1735 all future created toplevels as well.
1736
1737 The data in the images is taken as a snapshot at the time of
1738 invocation. If the images are later changed, this is not reflected
1739 to the titlebar icons. Multiple images are accepted to allow
1740 different images sizes to be provided. The window manager may scale
1741 provided icons to an appropriate size.
1742
1743 On Windows, the images are packed into a Windows icon structure.
1744 This will override an icon specified to wm_iconbitmap, and vice
1745 versa.
1746
1747 On X, the images are arranged into the _NET_WM_ICON X property,
1748 which most modern window managers support. An icon specified by
Berker Peksag4882cac2015-04-14 09:30:01 +03001749 wm_iconbitmap may exist simultaneously.
Martin v. Löwis5c3c4242012-03-13 13:40:42 -07001750
1751 On Macintosh, this currently does nothing."""
1752 if default:
1753 self.tk.call('wm', 'iconphoto', self._w, "-default", *args)
1754 else:
1755 self.tk.call('wm', 'iconphoto', self._w, *args)
1756 iconphoto = wm_iconphoto
Fredrik Lundh06d28152000-08-09 18:03:12 +00001757 def wm_iconposition(self, x=None, y=None):
1758 """Set the position of the icon of this widget to X and Y. Return
1759 a tuple of the current values of X and X if None is given."""
1760 return self._getints(self.tk.call(
1761 'wm', 'iconposition', self._w, x, y))
1762 iconposition = wm_iconposition
1763 def wm_iconwindow(self, pathName=None):
1764 """Set widget PATHNAME to be displayed instead of icon. Return the current
1765 value if None is given."""
1766 return self.tk.call('wm', 'iconwindow', self._w, pathName)
1767 iconwindow = wm_iconwindow
Martin v. Löwis5c3c4242012-03-13 13:40:42 -07001768 def wm_manage(self, widget): # new in Tk 8.5
1769 """The widget specified will become a stand alone top-level window.
1770 The window will be decorated with the window managers title bar,
1771 etc."""
1772 self.tk.call('wm', 'manage', widget)
1773 manage = wm_manage
Fredrik Lundh06d28152000-08-09 18:03:12 +00001774 def wm_maxsize(self, width=None, height=None):
1775 """Set max WIDTH and HEIGHT for this widget. If the window is gridded
1776 the values are given in grid units. Return the current values if None
1777 is given."""
1778 return self._getints(self.tk.call(
1779 'wm', 'maxsize', self._w, width, height))
1780 maxsize = wm_maxsize
1781 def wm_minsize(self, width=None, height=None):
1782 """Set min WIDTH and HEIGHT for this widget. If the window is gridded
1783 the values are given in grid units. Return the current values if None
1784 is given."""
1785 return self._getints(self.tk.call(
1786 'wm', 'minsize', self._w, width, height))
1787 minsize = wm_minsize
1788 def wm_overrideredirect(self, boolean=None):
1789 """Instruct the window manager to ignore this widget
1790 if BOOLEAN is given with 1. Return the current value if None
1791 is given."""
1792 return self._getboolean(self.tk.call(
1793 'wm', 'overrideredirect', self._w, boolean))
1794 overrideredirect = wm_overrideredirect
1795 def wm_positionfrom(self, who=None):
1796 """Instruct the window manager that the position of this widget shall
1797 be defined by the user if WHO is "user", and by its own policy if WHO is
1798 "program"."""
1799 return self.tk.call('wm', 'positionfrom', self._w, who)
1800 positionfrom = wm_positionfrom
1801 def wm_protocol(self, name=None, func=None):
1802 """Bind function FUNC to command NAME for this widget.
1803 Return the function bound to NAME if None is given. NAME could be
1804 e.g. "WM_SAVE_YOURSELF" or "WM_DELETE_WINDOW"."""
Florent Xicluna5d1155c2011-10-28 14:45:05 +02001805 if callable(func):
Fredrik Lundh06d28152000-08-09 18:03:12 +00001806 command = self._register(func)
1807 else:
1808 command = func
1809 return self.tk.call(
1810 'wm', 'protocol', self._w, name, command)
1811 protocol = wm_protocol
1812 def wm_resizable(self, width=None, height=None):
1813 """Instruct the window manager whether this width can be resized
1814 in WIDTH or HEIGHT. Both values are boolean values."""
1815 return self.tk.call('wm', 'resizable', self._w, width, height)
1816 resizable = wm_resizable
1817 def wm_sizefrom(self, who=None):
1818 """Instruct the window manager that the size of this widget shall
1819 be defined by the user if WHO is "user", and by its own policy if WHO is
1820 "program"."""
1821 return self.tk.call('wm', 'sizefrom', self._w, who)
1822 sizefrom = wm_sizefrom
Fredrik Lundh289ad8f2000-08-09 19:11:59 +00001823 def wm_state(self, newstate=None):
1824 """Query or set the state of this widget as one of normal, icon,
1825 iconic (see wm_iconwindow), withdrawn, or zoomed (Windows only)."""
1826 return self.tk.call('wm', 'state', self._w, newstate)
Fredrik Lundh06d28152000-08-09 18:03:12 +00001827 state = wm_state
1828 def wm_title(self, string=None):
1829 """Set the title of this widget."""
1830 return self.tk.call('wm', 'title', self._w, string)
1831 title = wm_title
1832 def wm_transient(self, master=None):
1833 """Instruct the window manager that this widget is transient
1834 with regard to widget MASTER."""
1835 return self.tk.call('wm', 'transient', self._w, master)
1836 transient = wm_transient
1837 def wm_withdraw(self):
1838 """Withdraw this widget from the screen such that it is unmapped
1839 and forgotten by the window manager. Re-draw it with wm_deiconify."""
1840 return self.tk.call('wm', 'withdraw', self._w)
1841 withdraw = wm_withdraw
Guido van Rossume365a591998-05-01 19:48:20 +00001842
Guido van Rossum18468821994-06-20 07:49:28 +00001843
1844class Tk(Misc, Wm):
Fredrik Lundh06d28152000-08-09 18:03:12 +00001845 """Toplevel widget of Tk which represents mostly the main window
Ezio Melotti42da6632011-03-15 05:18:48 +02001846 of an application. It has an associated Tcl interpreter."""
Fredrik Lundh06d28152000-08-09 18:03:12 +00001847 _w = '.'
Martin v. Löwis9441c072004-08-03 18:36:25 +00001848 def __init__(self, screenName=None, baseName=None, className='Tk',
1849 useTk=1, sync=0, use=None):
Fredrik Lundh06d28152000-08-09 18:03:12 +00001850 """Return a new Toplevel widget on screen SCREENNAME. A new Tcl interpreter will
1851 be created. BASENAME will be used for the identification of the profile file (see
1852 readprofile).
1853 It is constructed from sys.argv[0] without extensions if None is given. CLASSNAME
1854 is the name of the widget class."""
Fredrik Lundh06d28152000-08-09 18:03:12 +00001855 self.master = None
1856 self.children = {}
David Aschere2b4b322004-02-18 05:59:53 +00001857 self._tkloaded = 0
1858 # to avoid recursions in the getattr code in case of failure, we
1859 # ensure that self.tk is always _something_.
Tim Peters182b5ac2004-07-18 06:16:08 +00001860 self.tk = None
Fredrik Lundh06d28152000-08-09 18:03:12 +00001861 if baseName is None:
Florent Xicluna54540ec2011-11-04 08:29:17 +01001862 import os
Fredrik Lundh06d28152000-08-09 18:03:12 +00001863 baseName = os.path.basename(sys.argv[0])
1864 baseName, ext = os.path.splitext(baseName)
Brett Cannonf299abd2015-04-13 14:21:02 -04001865 if ext not in ('.py', '.pyc'):
Fredrik Lundh06d28152000-08-09 18:03:12 +00001866 baseName = baseName + ext
David Aschere2b4b322004-02-18 05:59:53 +00001867 interactive = 0
Martin v. Löwis9441c072004-08-03 18:36:25 +00001868 self.tk = _tkinter.create(screenName, baseName, className, interactive, wantobjects, useTk, sync, use)
David Aschere2b4b322004-02-18 05:59:53 +00001869 if useTk:
1870 self._loadtk()
Antoine Pitrou7ec3a322012-12-09 14:46:18 +01001871 if not sys.flags.ignore_environment:
1872 # Issue #16248: Honor the -E flag to avoid code injection.
1873 self.readprofile(baseName, className)
David Aschere2b4b322004-02-18 05:59:53 +00001874 def loadtk(self):
1875 if not self._tkloaded:
1876 self.tk.loadtk()
1877 self._loadtk()
1878 def _loadtk(self):
1879 self._tkloaded = 1
1880 global _default_root
Fredrik Lundh06d28152000-08-09 18:03:12 +00001881 # Version sanity checks
1882 tk_version = self.tk.getvar('tk_version')
1883 if tk_version != _tkinter.TK_VERSION:
Collin Winterce36ad82007-08-30 01:19:48 +00001884 raise RuntimeError("tk.h version (%s) doesn't match libtk.a version (%s)"
1885 % (_tkinter.TK_VERSION, tk_version))
Martin v. Löwis54895972003-05-24 11:37:15 +00001886 # Under unknown circumstances, tcl_version gets coerced to float
1887 tcl_version = str(self.tk.getvar('tcl_version'))
Fredrik Lundh06d28152000-08-09 18:03:12 +00001888 if tcl_version != _tkinter.TCL_VERSION:
Collin Winterce36ad82007-08-30 01:19:48 +00001889 raise RuntimeError("tcl.h version (%s) doesn't match libtcl.a version (%s)" \
1890 % (_tkinter.TCL_VERSION, tcl_version))
Fredrik Lundh06d28152000-08-09 18:03:12 +00001891 if TkVersion < 4.0:
Collin Winterce36ad82007-08-30 01:19:48 +00001892 raise RuntimeError("Tk 4.0 or higher is required; found Tk %s"
1893 % str(TkVersion))
Martin v. Löwis4afe1542005-03-01 08:09:28 +00001894 # Create and register the tkerror and exit commands
1895 # We need to inline parts of _register here, _ register
1896 # would register differently-named commands.
1897 if self._tclCommands is None:
1898 self._tclCommands = []
Fredrik Lundh06d28152000-08-09 18:03:12 +00001899 self.tk.createcommand('tkerror', _tkerror)
1900 self.tk.createcommand('exit', _exit)
Martin v. Löwis4afe1542005-03-01 08:09:28 +00001901 self._tclCommands.append('tkerror')
1902 self._tclCommands.append('exit')
Fredrik Lundh06d28152000-08-09 18:03:12 +00001903 if _support_default_root and not _default_root:
1904 _default_root = self
1905 self.protocol("WM_DELETE_WINDOW", self.destroy)
1906 def destroy(self):
1907 """Destroy this and all descendants widgets. This will
1908 end the application of this Tcl interpreter."""
Guido van Rossumb5a755e2007-07-18 18:15:48 +00001909 for c in list(self.children.values()): c.destroy()
Fredrik Lundh06d28152000-08-09 18:03:12 +00001910 self.tk.call('destroy', self._w)
1911 Misc.destroy(self)
1912 global _default_root
1913 if _support_default_root and _default_root is self:
1914 _default_root = None
1915 def readprofile(self, baseName, className):
1916 """Internal function. It reads BASENAME.tcl and CLASSNAME.tcl into
Neal Norwitz01688022007-08-12 00:43:29 +00001917 the Tcl Interpreter and calls exec on the contents of BASENAME.py and
1918 CLASSNAME.py if such a file exists in the home directory."""
Fredrik Lundh06d28152000-08-09 18:03:12 +00001919 import os
Guido van Rossume014a132006-08-19 16:53:45 +00001920 if 'HOME' in os.environ: home = os.environ['HOME']
Fredrik Lundh06d28152000-08-09 18:03:12 +00001921 else: home = os.curdir
1922 class_tcl = os.path.join(home, '.%s.tcl' % className)
1923 class_py = os.path.join(home, '.%s.py' % className)
1924 base_tcl = os.path.join(home, '.%s.tcl' % baseName)
1925 base_py = os.path.join(home, '.%s.py' % baseName)
1926 dir = {'self': self}
Georg Brandl14fc4272008-05-17 18:39:55 +00001927 exec('from tkinter import *', dir)
Fredrik Lundh06d28152000-08-09 18:03:12 +00001928 if os.path.isfile(class_tcl):
Fredrik Lundh06d28152000-08-09 18:03:12 +00001929 self.tk.call('source', class_tcl)
1930 if os.path.isfile(class_py):
Neal Norwitz01688022007-08-12 00:43:29 +00001931 exec(open(class_py).read(), dir)
Fredrik Lundh06d28152000-08-09 18:03:12 +00001932 if os.path.isfile(base_tcl):
Fredrik Lundh06d28152000-08-09 18:03:12 +00001933 self.tk.call('source', base_tcl)
1934 if os.path.isfile(base_py):
Neal Norwitz01688022007-08-12 00:43:29 +00001935 exec(open(base_py).read(), dir)
Fredrik Lundh06d28152000-08-09 18:03:12 +00001936 def report_callback_exception(self, exc, val, tb):
Serhiy Storchaka95024872014-09-14 21:17:32 +03001937 """Report callback exception on sys.stderr.
1938
1939 Applications may want to override this internal function, and
1940 should when sys.stderr is None."""
Florent Xicluna54540ec2011-11-04 08:29:17 +01001941 import traceback
Serhiy Storchaka95024872014-09-14 21:17:32 +03001942 print("Exception in Tkinter callback", file=sys.stderr)
Fredrik Lundh06d28152000-08-09 18:03:12 +00001943 sys.last_type = exc
1944 sys.last_value = val
1945 sys.last_traceback = tb
1946 traceback.print_exception(exc, val, tb)
David Aschere2b4b322004-02-18 05:59:53 +00001947 def __getattr__(self, attr):
1948 "Delegate attribute access to the interpreter object"
1949 return getattr(self.tk, attr)
Guido van Rossum18468821994-06-20 07:49:28 +00001950
Guido van Rossum368e06b1997-11-07 20:38:49 +00001951# Ideally, the classes Pack, Place and Grid disappear, the
1952# pack/place/grid methods are defined on the Widget class, and
1953# everybody uses w.pack_whatever(...) instead of Pack.whatever(w,
1954# ...), with pack(), place() and grid() being short for
1955# pack_configure(), place_configure() and grid_columnconfigure(), and
1956# forget() being short for pack_forget(). As a practical matter, I'm
1957# afraid that there is too much code out there that may be using the
1958# Pack, Place or Grid class, so I leave them intact -- but only as
1959# backwards compatibility features. Also note that those methods that
1960# take a master as argument (e.g. pack_propagate) have been moved to
1961# the Misc class (which now incorporates all methods common between
1962# toplevel and interior widgets). Again, for compatibility, these are
1963# copied into the Pack, Place or Grid class.
1964
David Aschere2b4b322004-02-18 05:59:53 +00001965
1966def Tcl(screenName=None, baseName=None, className='Tk', useTk=0):
1967 return Tk(screenName, baseName, className, useTk)
1968
Guido van Rossum18468821994-06-20 07:49:28 +00001969class Pack:
Fredrik Lundh06d28152000-08-09 18:03:12 +00001970 """Geometry manager Pack.
Guido van Rossum5917ecb2000-06-29 16:30:50 +00001971
Fredrik Lundh06d28152000-08-09 18:03:12 +00001972 Base class to use the methods pack_* in every widget."""
1973 def pack_configure(self, cnf={}, **kw):
1974 """Pack a widget in the parent widget. Use as options:
1975 after=widget - pack it after you have packed widget
1976 anchor=NSEW (or subset) - position widget according to
1977 given direction
Georg Brandlbf1eb632008-05-29 07:19:00 +00001978 before=widget - pack it before you will pack widget
Martin v. Löwisbfe175c2003-04-16 19:42:51 +00001979 expand=bool - expand widget if parent size grows
Fredrik Lundh06d28152000-08-09 18:03:12 +00001980 fill=NONE or X or Y or BOTH - fill widget if widget grows
1981 in=master - use master to contain this widget
Georg Brandlbf1eb632008-05-29 07:19:00 +00001982 in_=master - see 'in' option description
Fredrik Lundh06d28152000-08-09 18:03:12 +00001983 ipadx=amount - add internal padding in x direction
1984 ipady=amount - add internal padding in y direction
1985 padx=amount - add padding in x direction
1986 pady=amount - add padding in y direction
1987 side=TOP or BOTTOM or LEFT or RIGHT - where to add this widget.
1988 """
1989 self.tk.call(
1990 ('pack', 'configure', self._w)
1991 + self._options(cnf, kw))
1992 pack = configure = config = pack_configure
1993 def pack_forget(self):
1994 """Unmap this widget and do not use it for the packing order."""
1995 self.tk.call('pack', 'forget', self._w)
1996 forget = pack_forget
1997 def pack_info(self):
1998 """Return information about the packing options
1999 for this widget."""
Serhiy Storchaka8f0a1d02014-09-06 22:47:58 +03002000 d = _splitdict(self.tk, self.tk.call('pack', 'info', self._w))
2001 if 'in' in d:
2002 d['in'] = self.nametowidget(d['in'])
2003 return d
Fredrik Lundh06d28152000-08-09 18:03:12 +00002004 info = pack_info
2005 propagate = pack_propagate = Misc.pack_propagate
2006 slaves = pack_slaves = Misc.pack_slaves
Guido van Rossum18468821994-06-20 07:49:28 +00002007
2008class Place:
Fredrik Lundh06d28152000-08-09 18:03:12 +00002009 """Geometry manager Place.
Guido van Rossum5917ecb2000-06-29 16:30:50 +00002010
Fredrik Lundh06d28152000-08-09 18:03:12 +00002011 Base class to use the methods place_* in every widget."""
2012 def place_configure(self, cnf={}, **kw):
2013 """Place a widget in the parent widget. Use as options:
Georg Brandlbf1eb632008-05-29 07:19:00 +00002014 in=master - master relative to which the widget is placed
2015 in_=master - see 'in' option description
Fredrik Lundh06d28152000-08-09 18:03:12 +00002016 x=amount - locate anchor of this widget at position x of master
2017 y=amount - locate anchor of this widget at position y of master
2018 relx=amount - locate anchor of this widget between 0.0 and 1.0
2019 relative to width of master (1.0 is right edge)
Georg Brandlbf1eb632008-05-29 07:19:00 +00002020 rely=amount - locate anchor of this widget between 0.0 and 1.0
Fredrik Lundh06d28152000-08-09 18:03:12 +00002021 relative to height of master (1.0 is bottom edge)
Georg Brandlbf1eb632008-05-29 07:19:00 +00002022 anchor=NSEW (or subset) - position anchor according to given direction
Fredrik Lundh06d28152000-08-09 18:03:12 +00002023 width=amount - width of this widget in pixel
2024 height=amount - height of this widget in pixel
2025 relwidth=amount - width of this widget between 0.0 and 1.0
2026 relative to width of master (1.0 is the same width
Georg Brandlbf1eb632008-05-29 07:19:00 +00002027 as the master)
2028 relheight=amount - height of this widget between 0.0 and 1.0
Fredrik Lundh06d28152000-08-09 18:03:12 +00002029 relative to height of master (1.0 is the same
Georg Brandlbf1eb632008-05-29 07:19:00 +00002030 height as the master)
2031 bordermode="inside" or "outside" - whether to take border width of
2032 master widget into account
2033 """
Fredrik Lundh06d28152000-08-09 18:03:12 +00002034 self.tk.call(
2035 ('place', 'configure', self._w)
2036 + self._options(cnf, kw))
2037 place = configure = config = place_configure
2038 def place_forget(self):
2039 """Unmap this widget."""
2040 self.tk.call('place', 'forget', self._w)
2041 forget = place_forget
2042 def place_info(self):
2043 """Return information about the placing options
2044 for this widget."""
Serhiy Storchaka8f0a1d02014-09-06 22:47:58 +03002045 d = _splitdict(self.tk, self.tk.call('place', 'info', self._w))
2046 if 'in' in d:
2047 d['in'] = self.nametowidget(d['in'])
2048 return d
Fredrik Lundh06d28152000-08-09 18:03:12 +00002049 info = place_info
2050 slaves = place_slaves = Misc.place_slaves
Guido van Rossum18468821994-06-20 07:49:28 +00002051
Guido van Rossum37dcab11996-05-16 16:00:19 +00002052class Grid:
Fredrik Lundh06d28152000-08-09 18:03:12 +00002053 """Geometry manager Grid.
Guido van Rossum5917ecb2000-06-29 16:30:50 +00002054
Fredrik Lundh06d28152000-08-09 18:03:12 +00002055 Base class to use the methods grid_* in every widget."""
2056 # Thanks to Masazumi Yoshikawa (yosikawa@isi.edu)
2057 def grid_configure(self, cnf={}, **kw):
2058 """Position a widget in the parent widget in a grid. Use as options:
2059 column=number - use cell identified with given column (starting with 0)
2060 columnspan=number - this widget will span several columns
2061 in=master - use master to contain this widget
Georg Brandlbf1eb632008-05-29 07:19:00 +00002062 in_=master - see 'in' option description
Fredrik Lundh06d28152000-08-09 18:03:12 +00002063 ipadx=amount - add internal padding in x direction
2064 ipady=amount - add internal padding in y direction
2065 padx=amount - add padding in x direction
2066 pady=amount - add padding in y direction
2067 row=number - use cell identified with given row (starting with 0)
2068 rowspan=number - this widget will span several rows
2069 sticky=NSEW - if cell is larger on which sides will this
2070 widget stick to the cell boundary
2071 """
2072 self.tk.call(
2073 ('grid', 'configure', self._w)
2074 + self._options(cnf, kw))
2075 grid = configure = config = grid_configure
2076 bbox = grid_bbox = Misc.grid_bbox
2077 columnconfigure = grid_columnconfigure = Misc.grid_columnconfigure
2078 def grid_forget(self):
2079 """Unmap this widget."""
2080 self.tk.call('grid', 'forget', self._w)
2081 forget = grid_forget
2082 def grid_remove(self):
2083 """Unmap this widget but remember the grid options."""
2084 self.tk.call('grid', 'remove', self._w)
2085 def grid_info(self):
2086 """Return information about the options
2087 for positioning this widget in a grid."""
Serhiy Storchaka8f0a1d02014-09-06 22:47:58 +03002088 d = _splitdict(self.tk, self.tk.call('grid', 'info', self._w))
2089 if 'in' in d:
2090 d['in'] = self.nametowidget(d['in'])
2091 return d
Fredrik Lundh06d28152000-08-09 18:03:12 +00002092 info = grid_info
Martin v. Löwisdc579092001-10-13 09:33:51 +00002093 location = grid_location = Misc.grid_location
Fredrik Lundh06d28152000-08-09 18:03:12 +00002094 propagate = grid_propagate = Misc.grid_propagate
2095 rowconfigure = grid_rowconfigure = Misc.grid_rowconfigure
2096 size = grid_size = Misc.grid_size
2097 slaves = grid_slaves = Misc.grid_slaves
Guido van Rossum37dcab11996-05-16 16:00:19 +00002098
Guido van Rossum368e06b1997-11-07 20:38:49 +00002099class BaseWidget(Misc):
Fredrik Lundh06d28152000-08-09 18:03:12 +00002100 """Internal class."""
2101 def _setup(self, master, cnf):
2102 """Internal function. Sets up information about children."""
2103 if _support_default_root:
2104 global _default_root
2105 if not master:
2106 if not _default_root:
2107 _default_root = Tk()
2108 master = _default_root
2109 self.master = master
2110 self.tk = master.tk
2111 name = None
Guido van Rossume014a132006-08-19 16:53:45 +00002112 if 'name' in cnf:
Fredrik Lundh06d28152000-08-09 18:03:12 +00002113 name = cnf['name']
2114 del cnf['name']
2115 if not name:
Walter Dörwald70a6b492004-02-12 17:35:32 +00002116 name = repr(id(self))
Fredrik Lundh06d28152000-08-09 18:03:12 +00002117 self._name = name
2118 if master._w=='.':
2119 self._w = '.' + name
2120 else:
2121 self._w = master._w + '.' + name
2122 self.children = {}
Guido van Rossume014a132006-08-19 16:53:45 +00002123 if self._name in self.master.children:
Fredrik Lundh06d28152000-08-09 18:03:12 +00002124 self.master.children[self._name].destroy()
2125 self.master.children[self._name] = self
2126 def __init__(self, master, widgetName, cnf={}, kw={}, extra=()):
2127 """Construct a widget with the parent widget MASTER, a name WIDGETNAME
2128 and appropriate options."""
2129 if kw:
2130 cnf = _cnfmerge((cnf, kw))
2131 self.widgetName = widgetName
2132 BaseWidget._setup(self, master, cnf)
Hirokazu Yamamotoa18424c2008-11-04 06:26:27 +00002133 if self._tclCommands is None:
2134 self._tclCommands = []
Guilherme Polob212b752008-09-04 11:21:31 +00002135 classes = [(k, v) for k, v in cnf.items() if isinstance(k, type)]
2136 for k, v in classes:
2137 del cnf[k]
Fredrik Lundh06d28152000-08-09 18:03:12 +00002138 self.tk.call(
2139 (widgetName, self._w) + extra + self._options(cnf))
2140 for k, v in classes:
2141 k.configure(self, v)
2142 def destroy(self):
2143 """Destroy this and all descendants widgets."""
Guido van Rossum992d4a32007-07-11 13:09:30 +00002144 for c in list(self.children.values()): c.destroy()
Thomas Wouters0e3f5912006-08-11 14:57:12 +00002145 self.tk.call('destroy', self._w)
Guido van Rossume014a132006-08-19 16:53:45 +00002146 if self._name in self.master.children:
Fredrik Lundh06d28152000-08-09 18:03:12 +00002147 del self.master.children[self._name]
Fredrik Lundh06d28152000-08-09 18:03:12 +00002148 Misc.destroy(self)
2149 def _do(self, name, args=()):
2150 # XXX Obsolete -- better use self.tk.call directly!
2151 return self.tk.call((self._w, name) + args)
Guido van Rossum18468821994-06-20 07:49:28 +00002152
Guido van Rossum368e06b1997-11-07 20:38:49 +00002153class Widget(BaseWidget, Pack, Place, Grid):
Fredrik Lundh06d28152000-08-09 18:03:12 +00002154 """Internal class.
Guido van Rossum5917ecb2000-06-29 16:30:50 +00002155
Fredrik Lundh06d28152000-08-09 18:03:12 +00002156 Base class for a widget which can be positioned with the geometry managers
2157 Pack, Place or Grid."""
2158 pass
Guido van Rossum368e06b1997-11-07 20:38:49 +00002159
2160class Toplevel(BaseWidget, Wm):
Fredrik Lundh06d28152000-08-09 18:03:12 +00002161 """Toplevel widget, e.g. for dialogs."""
2162 def __init__(self, master=None, cnf={}, **kw):
2163 """Construct a toplevel widget with the parent MASTER.
Guido van Rossum5917ecb2000-06-29 16:30:50 +00002164
Fredrik Lundh06d28152000-08-09 18:03:12 +00002165 Valid resource names: background, bd, bg, borderwidth, class,
2166 colormap, container, cursor, height, highlightbackground,
2167 highlightcolor, highlightthickness, menu, relief, screen, takefocus,
2168 use, visual, width."""
2169 if kw:
2170 cnf = _cnfmerge((cnf, kw))
2171 extra = ()
2172 for wmkey in ['screen', 'class_', 'class', 'visual',
2173 'colormap']:
Guido van Rossume014a132006-08-19 16:53:45 +00002174 if wmkey in cnf:
Fredrik Lundh06d28152000-08-09 18:03:12 +00002175 val = cnf[wmkey]
2176 # TBD: a hack needed because some keys
2177 # are not valid as keyword arguments
2178 if wmkey[-1] == '_': opt = '-'+wmkey[:-1]
2179 else: opt = '-'+wmkey
2180 extra = extra + (opt, val)
2181 del cnf[wmkey]
2182 BaseWidget.__init__(self, master, 'toplevel', cnf, {}, extra)
2183 root = self._root()
2184 self.iconname(root.iconname())
2185 self.title(root.title())
2186 self.protocol("WM_DELETE_WINDOW", self.destroy)
Guido van Rossum18468821994-06-20 07:49:28 +00002187
2188class Button(Widget):
Fredrik Lundh06d28152000-08-09 18:03:12 +00002189 """Button widget."""
2190 def __init__(self, master=None, cnf={}, **kw):
2191 """Construct a button widget with the parent MASTER.
Raymond Hettingerff41c482003-04-06 09:01:11 +00002192
Martin v. Löwis2ec36272002-10-13 10:22:08 +00002193 STANDARD OPTIONS
Raymond Hettingerff41c482003-04-06 09:01:11 +00002194
Martin v. Löwis2ec36272002-10-13 10:22:08 +00002195 activebackground, activeforeground, anchor,
2196 background, bitmap, borderwidth, cursor,
Raymond Hettingerff41c482003-04-06 09:01:11 +00002197 disabledforeground, font, foreground
Martin v. Löwis2ec36272002-10-13 10:22:08 +00002198 highlightbackground, highlightcolor,
Raymond Hettingerff41c482003-04-06 09:01:11 +00002199 highlightthickness, image, justify,
Martin v. Löwis2ec36272002-10-13 10:22:08 +00002200 padx, pady, relief, repeatdelay,
Raymond Hettingerff41c482003-04-06 09:01:11 +00002201 repeatinterval, takefocus, text,
Martin v. Löwis2ec36272002-10-13 10:22:08 +00002202 textvariable, underline, wraplength
Raymond Hettingerff41c482003-04-06 09:01:11 +00002203
Martin v. Löwis2ec36272002-10-13 10:22:08 +00002204 WIDGET-SPECIFIC OPTIONS
Raymond Hettingerff41c482003-04-06 09:01:11 +00002205
Martin v. Löwis2ec36272002-10-13 10:22:08 +00002206 command, compound, default, height,
2207 overrelief, state, width
2208 """
Fredrik Lundh06d28152000-08-09 18:03:12 +00002209 Widget.__init__(self, master, 'button', cnf, kw)
Raymond Hettingerff41c482003-04-06 09:01:11 +00002210
Fredrik Lundh06d28152000-08-09 18:03:12 +00002211 def flash(self):
Raymond Hettingerff41c482003-04-06 09:01:11 +00002212 """Flash the button.
2213
2214 This is accomplished by redisplaying
2215 the button several times, alternating between active and
2216 normal colors. At the end of the flash the button is left
2217 in the same normal/active state as when the command was
2218 invoked. This command is ignored if the button's state is
Martin v. Löwis2ec36272002-10-13 10:22:08 +00002219 disabled.
2220 """
Fredrik Lundh06d28152000-08-09 18:03:12 +00002221 self.tk.call(self._w, 'flash')
Raymond Hettingerff41c482003-04-06 09:01:11 +00002222
Fredrik Lundh06d28152000-08-09 18:03:12 +00002223 def invoke(self):
Raymond Hettingerff41c482003-04-06 09:01:11 +00002224 """Invoke the command associated with the button.
2225
2226 The return value is the return value from the command,
Martin v. Löwis2ec36272002-10-13 10:22:08 +00002227 or an empty string if there is no command associated with
2228 the button. This command is ignored if the button's state
2229 is disabled.
2230 """
Fredrik Lundh06d28152000-08-09 18:03:12 +00002231 return self.tk.call(self._w, 'invoke')
Guido van Rossum18468821994-06-20 07:49:28 +00002232
Guilherme Polo1fff0082009-08-14 15:05:30 +00002233class Canvas(Widget, XView, YView):
Fredrik Lundh06d28152000-08-09 18:03:12 +00002234 """Canvas widget to display graphical elements like lines or text."""
2235 def __init__(self, master=None, cnf={}, **kw):
2236 """Construct a canvas widget with the parent MASTER.
Guido van Rossum5917ecb2000-06-29 16:30:50 +00002237
Fredrik Lundh06d28152000-08-09 18:03:12 +00002238 Valid resource names: background, bd, bg, borderwidth, closeenough,
2239 confine, cursor, height, highlightbackground, highlightcolor,
2240 highlightthickness, insertbackground, insertborderwidth,
2241 insertofftime, insertontime, insertwidth, offset, relief,
2242 scrollregion, selectbackground, selectborderwidth, selectforeground,
2243 state, takefocus, width, xscrollcommand, xscrollincrement,
2244 yscrollcommand, yscrollincrement."""
2245 Widget.__init__(self, master, 'canvas', cnf, kw)
2246 def addtag(self, *args):
2247 """Internal function."""
2248 self.tk.call((self._w, 'addtag') + args)
2249 def addtag_above(self, newtag, tagOrId):
2250 """Add tag NEWTAG to all items above TAGORID."""
2251 self.addtag(newtag, 'above', tagOrId)
2252 def addtag_all(self, newtag):
2253 """Add tag NEWTAG to all items."""
2254 self.addtag(newtag, 'all')
2255 def addtag_below(self, newtag, tagOrId):
2256 """Add tag NEWTAG to all items below TAGORID."""
2257 self.addtag(newtag, 'below', tagOrId)
2258 def addtag_closest(self, newtag, x, y, halo=None, start=None):
2259 """Add tag NEWTAG to item which is closest to pixel at X, Y.
2260 If several match take the top-most.
2261 All items closer than HALO are considered overlapping (all are
2262 closests). If START is specified the next below this tag is taken."""
2263 self.addtag(newtag, 'closest', x, y, halo, start)
2264 def addtag_enclosed(self, newtag, x1, y1, x2, y2):
2265 """Add tag NEWTAG to all items in the rectangle defined
2266 by X1,Y1,X2,Y2."""
2267 self.addtag(newtag, 'enclosed', x1, y1, x2, y2)
2268 def addtag_overlapping(self, newtag, x1, y1, x2, y2):
2269 """Add tag NEWTAG to all items which overlap the rectangle
2270 defined by X1,Y1,X2,Y2."""
2271 self.addtag(newtag, 'overlapping', x1, y1, x2, y2)
2272 def addtag_withtag(self, newtag, tagOrId):
2273 """Add tag NEWTAG to all items with TAGORID."""
2274 self.addtag(newtag, 'withtag', tagOrId)
2275 def bbox(self, *args):
2276 """Return a tuple of X1,Y1,X2,Y2 coordinates for a rectangle
2277 which encloses all items with tags specified as arguments."""
2278 return self._getints(
2279 self.tk.call((self._w, 'bbox') + args)) or None
2280 def tag_unbind(self, tagOrId, sequence, funcid=None):
2281 """Unbind for all items with TAGORID for event SEQUENCE the
2282 function identified with FUNCID."""
2283 self.tk.call(self._w, 'bind', tagOrId, sequence, '')
2284 if funcid:
2285 self.deletecommand(funcid)
2286 def tag_bind(self, tagOrId, sequence=None, func=None, add=None):
2287 """Bind to all items with TAGORID at event SEQUENCE a call to function FUNC.
Guido van Rossum5917ecb2000-06-29 16:30:50 +00002288
Fredrik Lundh06d28152000-08-09 18:03:12 +00002289 An additional boolean parameter ADD specifies whether FUNC will be
2290 called additionally to the other bound function or whether it will
2291 replace the previous function. See bind for the return value."""
2292 return self._bind((self._w, 'bind', tagOrId),
2293 sequence, func, add)
2294 def canvasx(self, screenx, gridspacing=None):
2295 """Return the canvas x coordinate of pixel position SCREENX rounded
2296 to nearest multiple of GRIDSPACING units."""
Serhiy Storchaka645058d2015-05-06 14:00:04 +03002297 return self.tk.getdouble(self.tk.call(
Fredrik Lundh06d28152000-08-09 18:03:12 +00002298 self._w, 'canvasx', screenx, gridspacing))
2299 def canvasy(self, screeny, gridspacing=None):
2300 """Return the canvas y coordinate of pixel position SCREENY rounded
2301 to nearest multiple of GRIDSPACING units."""
Serhiy Storchaka645058d2015-05-06 14:00:04 +03002302 return self.tk.getdouble(self.tk.call(
Fredrik Lundh06d28152000-08-09 18:03:12 +00002303 self._w, 'canvasy', screeny, gridspacing))
2304 def coords(self, *args):
2305 """Return a list of coordinates for the item given in ARGS."""
2306 # XXX Should use _flatten on args
Serhiy Storchaka645058d2015-05-06 14:00:04 +03002307 return [self.tk.getdouble(x) for x in
Guido van Rossum0bd54331998-05-19 21:18:13 +00002308 self.tk.splitlist(
Alexander Belopolsky022f0492010-11-22 19:40:51 +00002309 self.tk.call((self._w, 'coords') + args))]
Fredrik Lundh06d28152000-08-09 18:03:12 +00002310 def _create(self, itemType, args, kw): # Args: (val, val, ..., cnf={})
2311 """Internal function."""
2312 args = _flatten(args)
2313 cnf = args[-1]
Guido van Rossum13257902007-06-07 23:15:56 +00002314 if isinstance(cnf, (dict, tuple)):
Fredrik Lundh06d28152000-08-09 18:03:12 +00002315 args = args[:-1]
2316 else:
2317 cnf = {}
Serhiy Storchaka645058d2015-05-06 14:00:04 +03002318 return self.tk.getint(self.tk.call(
Raymond Hettingerff41c482003-04-06 09:01:11 +00002319 self._w, 'create', itemType,
2320 *(args + self._options(cnf, kw))))
Fredrik Lundh06d28152000-08-09 18:03:12 +00002321 def create_arc(self, *args, **kw):
2322 """Create arc shaped region with coordinates x1,y1,x2,y2."""
2323 return self._create('arc', args, kw)
2324 def create_bitmap(self, *args, **kw):
2325 """Create bitmap with coordinates x1,y1."""
2326 return self._create('bitmap', args, kw)
2327 def create_image(self, *args, **kw):
2328 """Create image item with coordinates x1,y1."""
2329 return self._create('image', args, kw)
2330 def create_line(self, *args, **kw):
2331 """Create line with coordinates x1,y1,...,xn,yn."""
2332 return self._create('line', args, kw)
2333 def create_oval(self, *args, **kw):
2334 """Create oval with coordinates x1,y1,x2,y2."""
2335 return self._create('oval', args, kw)
2336 def create_polygon(self, *args, **kw):
2337 """Create polygon with coordinates x1,y1,...,xn,yn."""
2338 return self._create('polygon', args, kw)
2339 def create_rectangle(self, *args, **kw):
2340 """Create rectangle with coordinates x1,y1,x2,y2."""
2341 return self._create('rectangle', args, kw)
2342 def create_text(self, *args, **kw):
2343 """Create text with coordinates x1,y1."""
2344 return self._create('text', args, kw)
2345 def create_window(self, *args, **kw):
2346 """Create window with coordinates x1,y1,x2,y2."""
2347 return self._create('window', args, kw)
2348 def dchars(self, *args):
2349 """Delete characters of text items identified by tag or id in ARGS (possibly
2350 several times) from FIRST to LAST character (including)."""
2351 self.tk.call((self._w, 'dchars') + args)
2352 def delete(self, *args):
2353 """Delete items identified by all tag or ids contained in ARGS."""
2354 self.tk.call((self._w, 'delete') + args)
2355 def dtag(self, *args):
2356 """Delete tag or id given as last arguments in ARGS from items
2357 identified by first argument in ARGS."""
2358 self.tk.call((self._w, 'dtag') + args)
2359 def find(self, *args):
2360 """Internal function."""
2361 return self._getints(
2362 self.tk.call((self._w, 'find') + args)) or ()
2363 def find_above(self, tagOrId):
2364 """Return items above TAGORID."""
2365 return self.find('above', tagOrId)
2366 def find_all(self):
2367 """Return all items."""
2368 return self.find('all')
2369 def find_below(self, tagOrId):
2370 """Return all items below TAGORID."""
2371 return self.find('below', tagOrId)
2372 def find_closest(self, x, y, halo=None, start=None):
2373 """Return item which is closest to pixel at X, Y.
2374 If several match take the top-most.
2375 All items closer than HALO are considered overlapping (all are
2376 closests). If START is specified the next below this tag is taken."""
2377 return self.find('closest', x, y, halo, start)
2378 def find_enclosed(self, x1, y1, x2, y2):
2379 """Return all items in rectangle defined
2380 by X1,Y1,X2,Y2."""
2381 return self.find('enclosed', x1, y1, x2, y2)
2382 def find_overlapping(self, x1, y1, x2, y2):
2383 """Return all items which overlap the rectangle
2384 defined by X1,Y1,X2,Y2."""
2385 return self.find('overlapping', x1, y1, x2, y2)
2386 def find_withtag(self, tagOrId):
2387 """Return all items with TAGORID."""
2388 return self.find('withtag', tagOrId)
2389 def focus(self, *args):
2390 """Set focus to the first item specified in ARGS."""
2391 return self.tk.call((self._w, 'focus') + args)
2392 def gettags(self, *args):
2393 """Return tags associated with the first item specified in ARGS."""
2394 return self.tk.splitlist(
2395 self.tk.call((self._w, 'gettags') + args))
2396 def icursor(self, *args):
2397 """Set cursor at position POS in the item identified by TAGORID.
2398 In ARGS TAGORID must be first."""
2399 self.tk.call((self._w, 'icursor') + args)
2400 def index(self, *args):
2401 """Return position of cursor as integer in item specified in ARGS."""
Serhiy Storchaka645058d2015-05-06 14:00:04 +03002402 return self.tk.getint(self.tk.call((self._w, 'index') + args))
Fredrik Lundh06d28152000-08-09 18:03:12 +00002403 def insert(self, *args):
2404 """Insert TEXT in item TAGORID at position POS. ARGS must
2405 be TAGORID POS TEXT."""
2406 self.tk.call((self._w, 'insert') + args)
2407 def itemcget(self, tagOrId, option):
2408 """Return the resource value for an OPTION for item TAGORID."""
2409 return self.tk.call(
2410 (self._w, 'itemcget') + (tagOrId, '-'+option))
2411 def itemconfigure(self, tagOrId, cnf=None, **kw):
2412 """Configure resources of an item TAGORID.
Guido van Rossum5917ecb2000-06-29 16:30:50 +00002413
Fredrik Lundh06d28152000-08-09 18:03:12 +00002414 The values for resources are specified as keyword
2415 arguments. To get an overview about
2416 the allowed keyword arguments call the method without arguments.
2417 """
Martin v. Löwis6ce13152002-10-10 14:36:13 +00002418 return self._configure(('itemconfigure', tagOrId), cnf, kw)
Fredrik Lundh06d28152000-08-09 18:03:12 +00002419 itemconfig = itemconfigure
2420 # lower, tkraise/lift hide Misc.lower, Misc.tkraise/lift,
2421 # so the preferred name for them is tag_lower, tag_raise
2422 # (similar to tag_bind, and similar to the Text widget);
2423 # unfortunately can't delete the old ones yet (maybe in 1.6)
2424 def tag_lower(self, *args):
2425 """Lower an item TAGORID given in ARGS
2426 (optional below another item)."""
2427 self.tk.call((self._w, 'lower') + args)
2428 lower = tag_lower
2429 def move(self, *args):
2430 """Move an item TAGORID given in ARGS."""
2431 self.tk.call((self._w, 'move') + args)
2432 def postscript(self, cnf={}, **kw):
2433 """Print the contents of the canvas to a postscript
2434 file. Valid options: colormap, colormode, file, fontmap,
2435 height, pageanchor, pageheight, pagewidth, pagex, pagey,
2436 rotate, witdh, x, y."""
2437 return self.tk.call((self._w, 'postscript') +
2438 self._options(cnf, kw))
2439 def tag_raise(self, *args):
2440 """Raise an item TAGORID given in ARGS
2441 (optional above another item)."""
2442 self.tk.call((self._w, 'raise') + args)
2443 lift = tkraise = tag_raise
2444 def scale(self, *args):
2445 """Scale item TAGORID with XORIGIN, YORIGIN, XSCALE, YSCALE."""
2446 self.tk.call((self._w, 'scale') + args)
2447 def scan_mark(self, x, y):
2448 """Remember the current X, Y coordinates."""
2449 self.tk.call(self._w, 'scan', 'mark', x, y)
Neal Norwitze931ed52003-01-10 23:24:32 +00002450 def scan_dragto(self, x, y, gain=10):
2451 """Adjust the view of the canvas to GAIN times the
Fredrik Lundh06d28152000-08-09 18:03:12 +00002452 difference between X and Y and the coordinates given in
2453 scan_mark."""
Neal Norwitze931ed52003-01-10 23:24:32 +00002454 self.tk.call(self._w, 'scan', 'dragto', x, y, gain)
Fredrik Lundh06d28152000-08-09 18:03:12 +00002455 def select_adjust(self, tagOrId, index):
2456 """Adjust the end of the selection near the cursor of an item TAGORID to index."""
2457 self.tk.call(self._w, 'select', 'adjust', tagOrId, index)
2458 def select_clear(self):
2459 """Clear the selection if it is in this widget."""
2460 self.tk.call(self._w, 'select', 'clear')
2461 def select_from(self, tagOrId, index):
2462 """Set the fixed end of a selection in item TAGORID to INDEX."""
2463 self.tk.call(self._w, 'select', 'from', tagOrId, index)
2464 def select_item(self):
2465 """Return the item which has the selection."""
Neal Norwitz58b63bf2002-07-23 02:52:58 +00002466 return self.tk.call(self._w, 'select', 'item') or None
Fredrik Lundh06d28152000-08-09 18:03:12 +00002467 def select_to(self, tagOrId, index):
2468 """Set the variable end of a selection in item TAGORID to INDEX."""
2469 self.tk.call(self._w, 'select', 'to', tagOrId, index)
2470 def type(self, tagOrId):
2471 """Return the type of the item TAGORID."""
2472 return self.tk.call(self._w, 'type', tagOrId) or None
Guido van Rossum18468821994-06-20 07:49:28 +00002473
2474class Checkbutton(Widget):
Fredrik Lundh06d28152000-08-09 18:03:12 +00002475 """Checkbutton widget which is either in on- or off-state."""
2476 def __init__(self, master=None, cnf={}, **kw):
2477 """Construct a checkbutton widget with the parent MASTER.
Guido van Rossum5917ecb2000-06-29 16:30:50 +00002478
Fredrik Lundh06d28152000-08-09 18:03:12 +00002479 Valid resource names: activebackground, activeforeground, anchor,
2480 background, bd, bg, bitmap, borderwidth, command, cursor,
2481 disabledforeground, fg, font, foreground, height,
2482 highlightbackground, highlightcolor, highlightthickness, image,
2483 indicatoron, justify, offvalue, onvalue, padx, pady, relief,
2484 selectcolor, selectimage, state, takefocus, text, textvariable,
2485 underline, variable, width, wraplength."""
2486 Widget.__init__(self, master, 'checkbutton', cnf, kw)
2487 def deselect(self):
2488 """Put the button in off-state."""
2489 self.tk.call(self._w, 'deselect')
2490 def flash(self):
2491 """Flash the button."""
2492 self.tk.call(self._w, 'flash')
2493 def invoke(self):
2494 """Toggle the button and invoke a command if given as resource."""
2495 return self.tk.call(self._w, 'invoke')
2496 def select(self):
2497 """Put the button in on-state."""
2498 self.tk.call(self._w, 'select')
2499 def toggle(self):
2500 """Toggle the button."""
2501 self.tk.call(self._w, 'toggle')
Guido van Rossum18468821994-06-20 07:49:28 +00002502
Guilherme Polo1fff0082009-08-14 15:05:30 +00002503class Entry(Widget, XView):
Martin Panterc04fb562016-02-10 05:44:01 +00002504 """Entry widget which allows displaying simple text."""
Fredrik Lundh06d28152000-08-09 18:03:12 +00002505 def __init__(self, master=None, cnf={}, **kw):
2506 """Construct an entry widget with the parent MASTER.
Guido van Rossum5917ecb2000-06-29 16:30:50 +00002507
Fredrik Lundh06d28152000-08-09 18:03:12 +00002508 Valid resource names: background, bd, bg, borderwidth, cursor,
2509 exportselection, fg, font, foreground, highlightbackground,
2510 highlightcolor, highlightthickness, insertbackground,
2511 insertborderwidth, insertofftime, insertontime, insertwidth,
2512 invalidcommand, invcmd, justify, relief, selectbackground,
2513 selectborderwidth, selectforeground, show, state, takefocus,
2514 textvariable, validate, validatecommand, vcmd, width,
2515 xscrollcommand."""
2516 Widget.__init__(self, master, 'entry', cnf, kw)
2517 def delete(self, first, last=None):
2518 """Delete text from FIRST to LAST (not included)."""
2519 self.tk.call(self._w, 'delete', first, last)
2520 def get(self):
2521 """Return the text."""
2522 return self.tk.call(self._w, 'get')
2523 def icursor(self, index):
2524 """Insert cursor at INDEX."""
2525 self.tk.call(self._w, 'icursor', index)
2526 def index(self, index):
2527 """Return position of cursor."""
Serhiy Storchaka645058d2015-05-06 14:00:04 +03002528 return self.tk.getint(self.tk.call(
Fredrik Lundh06d28152000-08-09 18:03:12 +00002529 self._w, 'index', index))
2530 def insert(self, index, string):
2531 """Insert STRING at INDEX."""
2532 self.tk.call(self._w, 'insert', index, string)
2533 def scan_mark(self, x):
2534 """Remember the current X, Y coordinates."""
2535 self.tk.call(self._w, 'scan', 'mark', x)
2536 def scan_dragto(self, x):
2537 """Adjust the view of the canvas to 10 times the
2538 difference between X and Y and the coordinates given in
2539 scan_mark."""
2540 self.tk.call(self._w, 'scan', 'dragto', x)
2541 def selection_adjust(self, index):
2542 """Adjust the end of the selection near the cursor to INDEX."""
2543 self.tk.call(self._w, 'selection', 'adjust', index)
2544 select_adjust = selection_adjust
2545 def selection_clear(self):
2546 """Clear the selection if it is in this widget."""
2547 self.tk.call(self._w, 'selection', 'clear')
2548 select_clear = selection_clear
2549 def selection_from(self, index):
2550 """Set the fixed end of a selection to INDEX."""
2551 self.tk.call(self._w, 'selection', 'from', index)
2552 select_from = selection_from
2553 def selection_present(self):
Guilherme Polo1fff0082009-08-14 15:05:30 +00002554 """Return True if there are characters selected in the entry, False
2555 otherwise."""
Fredrik Lundh06d28152000-08-09 18:03:12 +00002556 return self.tk.getboolean(
2557 self.tk.call(self._w, 'selection', 'present'))
2558 select_present = selection_present
2559 def selection_range(self, start, end):
2560 """Set the selection from START to END (not included)."""
2561 self.tk.call(self._w, 'selection', 'range', start, end)
2562 select_range = selection_range
2563 def selection_to(self, index):
2564 """Set the variable end of a selection to INDEX."""
2565 self.tk.call(self._w, 'selection', 'to', index)
2566 select_to = selection_to
Guido van Rossum18468821994-06-20 07:49:28 +00002567
2568class Frame(Widget):
Fredrik Lundh06d28152000-08-09 18:03:12 +00002569 """Frame widget which may contain other widgets and can have a 3D border."""
2570 def __init__(self, master=None, cnf={}, **kw):
2571 """Construct a frame widget with the parent MASTER.
Guido van Rossum5917ecb2000-06-29 16:30:50 +00002572
Fredrik Lundh06d28152000-08-09 18:03:12 +00002573 Valid resource names: background, bd, bg, borderwidth, class,
2574 colormap, container, cursor, height, highlightbackground,
2575 highlightcolor, highlightthickness, relief, takefocus, visual, width."""
2576 cnf = _cnfmerge((cnf, kw))
2577 extra = ()
Guido van Rossume014a132006-08-19 16:53:45 +00002578 if 'class_' in cnf:
Fredrik Lundh06d28152000-08-09 18:03:12 +00002579 extra = ('-class', cnf['class_'])
2580 del cnf['class_']
Guido van Rossume014a132006-08-19 16:53:45 +00002581 elif 'class' in cnf:
Fredrik Lundh06d28152000-08-09 18:03:12 +00002582 extra = ('-class', cnf['class'])
2583 del cnf['class']
2584 Widget.__init__(self, master, 'frame', cnf, {}, extra)
Guido van Rossum18468821994-06-20 07:49:28 +00002585
2586class Label(Widget):
Fredrik Lundh06d28152000-08-09 18:03:12 +00002587 """Label widget which can display text and bitmaps."""
2588 def __init__(self, master=None, cnf={}, **kw):
2589 """Construct a label widget with the parent MASTER.
Raymond Hettingerff41c482003-04-06 09:01:11 +00002590
Martin v. Löwis2ec36272002-10-13 10:22:08 +00002591 STANDARD OPTIONS
Raymond Hettingerff41c482003-04-06 09:01:11 +00002592
2593 activebackground, activeforeground, anchor,
2594 background, bitmap, borderwidth, cursor,
Martin v. Löwis2ec36272002-10-13 10:22:08 +00002595 disabledforeground, font, foreground,
Raymond Hettingerff41c482003-04-06 09:01:11 +00002596 highlightbackground, highlightcolor,
2597 highlightthickness, image, justify,
2598 padx, pady, relief, takefocus, text,
Martin v. Löwis2ec36272002-10-13 10:22:08 +00002599 textvariable, underline, wraplength
Raymond Hettingerff41c482003-04-06 09:01:11 +00002600
Martin v. Löwis2ec36272002-10-13 10:22:08 +00002601 WIDGET-SPECIFIC OPTIONS
Raymond Hettingerff41c482003-04-06 09:01:11 +00002602
Martin v. Löwis2ec36272002-10-13 10:22:08 +00002603 height, state, width
Raymond Hettingerff41c482003-04-06 09:01:11 +00002604
Martin v. Löwis2ec36272002-10-13 10:22:08 +00002605 """
Fredrik Lundh06d28152000-08-09 18:03:12 +00002606 Widget.__init__(self, master, 'label', cnf, kw)
Guido van Rossum761c5ab1995-07-14 15:29:10 +00002607
Guilherme Polo1fff0082009-08-14 15:05:30 +00002608class Listbox(Widget, XView, YView):
Fredrik Lundh06d28152000-08-09 18:03:12 +00002609 """Listbox widget which can display a list of strings."""
2610 def __init__(self, master=None, cnf={}, **kw):
2611 """Construct a listbox widget with the parent MASTER.
Guido van Rossum5917ecb2000-06-29 16:30:50 +00002612
Fredrik Lundh06d28152000-08-09 18:03:12 +00002613 Valid resource names: background, bd, bg, borderwidth, cursor,
2614 exportselection, fg, font, foreground, height, highlightbackground,
2615 highlightcolor, highlightthickness, relief, selectbackground,
2616 selectborderwidth, selectforeground, selectmode, setgrid, takefocus,
2617 width, xscrollcommand, yscrollcommand, listvariable."""
2618 Widget.__init__(self, master, 'listbox', cnf, kw)
2619 def activate(self, index):
2620 """Activate item identified by INDEX."""
2621 self.tk.call(self._w, 'activate', index)
Serhiy Storchakafc14ad92014-06-02 21:31:07 +03002622 def bbox(self, index):
Fredrik Lundh06d28152000-08-09 18:03:12 +00002623 """Return a tuple of X1,Y1,X2,Y2 coordinates for a rectangle
Serhiy Storchakafc14ad92014-06-02 21:31:07 +03002624 which encloses the item identified by the given index."""
2625 return self._getints(self.tk.call(self._w, 'bbox', index)) or None
Fredrik Lundh06d28152000-08-09 18:03:12 +00002626 def curselection(self):
Serhiy Storchakafc14ad92014-06-02 21:31:07 +03002627 """Return the indices of currently selected item."""
2628 return self._getints(self.tk.call(self._w, 'curselection')) or ()
Fredrik Lundh06d28152000-08-09 18:03:12 +00002629 def delete(self, first, last=None):
Serhiy Storchakaca3cd002014-06-02 16:51:44 +03002630 """Delete items from FIRST to LAST (included)."""
Fredrik Lundh06d28152000-08-09 18:03:12 +00002631 self.tk.call(self._w, 'delete', first, last)
2632 def get(self, first, last=None):
Serhiy Storchakaca3cd002014-06-02 16:51:44 +03002633 """Get list of items from FIRST to LAST (included)."""
Serhiy Storchakafc14ad92014-06-02 21:31:07 +03002634 if last is not None:
Fredrik Lundh06d28152000-08-09 18:03:12 +00002635 return self.tk.splitlist(self.tk.call(
2636 self._w, 'get', first, last))
2637 else:
2638 return self.tk.call(self._w, 'get', first)
2639 def index(self, index):
2640 """Return index of item identified with INDEX."""
2641 i = self.tk.call(self._w, 'index', index)
2642 if i == 'none': return None
Serhiy Storchaka645058d2015-05-06 14:00:04 +03002643 return self.tk.getint(i)
Fredrik Lundh06d28152000-08-09 18:03:12 +00002644 def insert(self, index, *elements):
2645 """Insert ELEMENTS at INDEX."""
2646 self.tk.call((self._w, 'insert', index) + elements)
2647 def nearest(self, y):
2648 """Get index of item which is nearest to y coordinate Y."""
Serhiy Storchaka645058d2015-05-06 14:00:04 +03002649 return self.tk.getint(self.tk.call(
Fredrik Lundh06d28152000-08-09 18:03:12 +00002650 self._w, 'nearest', y))
2651 def scan_mark(self, x, y):
2652 """Remember the current X, Y coordinates."""
2653 self.tk.call(self._w, 'scan', 'mark', x, y)
2654 def scan_dragto(self, x, y):
2655 """Adjust the view of the listbox to 10 times the
2656 difference between X and Y and the coordinates given in
2657 scan_mark."""
2658 self.tk.call(self._w, 'scan', 'dragto', x, y)
2659 def see(self, index):
2660 """Scroll such that INDEX is visible."""
2661 self.tk.call(self._w, 'see', index)
2662 def selection_anchor(self, index):
2663 """Set the fixed end oft the selection to INDEX."""
2664 self.tk.call(self._w, 'selection', 'anchor', index)
2665 select_anchor = selection_anchor
2666 def selection_clear(self, first, last=None):
Serhiy Storchakaca3cd002014-06-02 16:51:44 +03002667 """Clear the selection from FIRST to LAST (included)."""
Fredrik Lundh06d28152000-08-09 18:03:12 +00002668 self.tk.call(self._w,
2669 'selection', 'clear', first, last)
2670 select_clear = selection_clear
2671 def selection_includes(self, index):
2672 """Return 1 if INDEX is part of the selection."""
2673 return self.tk.getboolean(self.tk.call(
2674 self._w, 'selection', 'includes', index))
2675 select_includes = selection_includes
2676 def selection_set(self, first, last=None):
Serhiy Storchakaca3cd002014-06-02 16:51:44 +03002677 """Set the selection from FIRST to LAST (included) without
Fredrik Lundh06d28152000-08-09 18:03:12 +00002678 changing the currently selected elements."""
2679 self.tk.call(self._w, 'selection', 'set', first, last)
2680 select_set = selection_set
2681 def size(self):
2682 """Return the number of elements in the listbox."""
Serhiy Storchaka645058d2015-05-06 14:00:04 +03002683 return self.tk.getint(self.tk.call(self._w, 'size'))
Guido van Rossum09f1ad82001-09-05 19:29:56 +00002684 def itemcget(self, index, option):
2685 """Return the resource value for an ITEM and an OPTION."""
2686 return self.tk.call(
2687 (self._w, 'itemcget') + (index, '-'+option))
Guido van Rossuma0adb922001-09-01 18:29:55 +00002688 def itemconfigure(self, index, cnf=None, **kw):
Guido van Rossum09f1ad82001-09-05 19:29:56 +00002689 """Configure resources of an ITEM.
Guido van Rossuma0adb922001-09-01 18:29:55 +00002690
2691 The values for resources are specified as keyword arguments.
2692 To get an overview about the allowed keyword arguments
2693 call the method without arguments.
2694 Valid resource names: background, bg, foreground, fg,
2695 selectbackground, selectforeground."""
Martin v. Löwis6ce13152002-10-10 14:36:13 +00002696 return self._configure(('itemconfigure', index), cnf, kw)
Guido van Rossuma0adb922001-09-01 18:29:55 +00002697 itemconfig = itemconfigure
Guido van Rossum18468821994-06-20 07:49:28 +00002698
2699class Menu(Widget):
Martin Panterc04fb562016-02-10 05:44:01 +00002700 """Menu widget which allows displaying menu bars, pull-down menus and pop-up menus."""
Fredrik Lundh06d28152000-08-09 18:03:12 +00002701 def __init__(self, master=None, cnf={}, **kw):
2702 """Construct menu widget with the parent MASTER.
Guido van Rossum5917ecb2000-06-29 16:30:50 +00002703
Fredrik Lundh06d28152000-08-09 18:03:12 +00002704 Valid resource names: activebackground, activeborderwidth,
2705 activeforeground, background, bd, bg, borderwidth, cursor,
2706 disabledforeground, fg, font, foreground, postcommand, relief,
2707 selectcolor, takefocus, tearoff, tearoffcommand, title, type."""
2708 Widget.__init__(self, master, 'menu', cnf, kw)
Fredrik Lundh06d28152000-08-09 18:03:12 +00002709 def tk_popup(self, x, y, entry=""):
2710 """Post the menu at position X,Y with entry ENTRY."""
2711 self.tk.call('tk_popup', self._w, x, y, entry)
Fredrik Lundh06d28152000-08-09 18:03:12 +00002712 def tk_bindForTraversal(self):
Serhiy Storchaka1a901cc2014-07-25 12:24:07 +03002713 # obsolete since Tk 4.0
2714 import warnings
2715 warnings.warn('tk_bindForTraversal() does nothing and '
2716 'will be removed in 3.6',
2717 DeprecationWarning, stacklevel=2)
Fredrik Lundh06d28152000-08-09 18:03:12 +00002718 def activate(self, index):
2719 """Activate entry at INDEX."""
2720 self.tk.call(self._w, 'activate', index)
2721 def add(self, itemType, cnf={}, **kw):
2722 """Internal function."""
2723 self.tk.call((self._w, 'add', itemType) +
2724 self._options(cnf, kw))
2725 def add_cascade(self, cnf={}, **kw):
2726 """Add hierarchical menu item."""
2727 self.add('cascade', cnf or kw)
2728 def add_checkbutton(self, cnf={}, **kw):
2729 """Add checkbutton menu item."""
2730 self.add('checkbutton', cnf or kw)
2731 def add_command(self, cnf={}, **kw):
2732 """Add command menu item."""
2733 self.add('command', cnf or kw)
2734 def add_radiobutton(self, cnf={}, **kw):
2735 """Addd radio menu item."""
2736 self.add('radiobutton', cnf or kw)
2737 def add_separator(self, cnf={}, **kw):
2738 """Add separator."""
2739 self.add('separator', cnf or kw)
2740 def insert(self, index, itemType, cnf={}, **kw):
2741 """Internal function."""
2742 self.tk.call((self._w, 'insert', index, itemType) +
2743 self._options(cnf, kw))
2744 def insert_cascade(self, index, cnf={}, **kw):
2745 """Add hierarchical menu item at INDEX."""
2746 self.insert(index, 'cascade', cnf or kw)
2747 def insert_checkbutton(self, index, cnf={}, **kw):
2748 """Add checkbutton menu item at INDEX."""
2749 self.insert(index, 'checkbutton', cnf or kw)
2750 def insert_command(self, index, cnf={}, **kw):
2751 """Add command menu item at INDEX."""
2752 self.insert(index, 'command', cnf or kw)
2753 def insert_radiobutton(self, index, cnf={}, **kw):
2754 """Addd radio menu item at INDEX."""
2755 self.insert(index, 'radiobutton', cnf or kw)
2756 def insert_separator(self, index, cnf={}, **kw):
2757 """Add separator at INDEX."""
2758 self.insert(index, 'separator', cnf or kw)
2759 def delete(self, index1, index2=None):
Hirokazu Yamamotoa18424c2008-11-04 06:26:27 +00002760 """Delete menu items between INDEX1 and INDEX2 (included)."""
Robert Schuppenies3d1c7de2008-08-10 11:28:17 +00002761 if index2 is None:
2762 index2 = index1
Robert Schuppenies3d1c7de2008-08-10 11:28:17 +00002763
Hirokazu Yamamotoa18424c2008-11-04 06:26:27 +00002764 num_index1, num_index2 = self.index(index1), self.index(index2)
2765 if (num_index1 is None) or (num_index2 is None):
2766 num_index1, num_index2 = 0, -1
2767
2768 for i in range(num_index1, num_index2 + 1):
2769 if 'command' in self.entryconfig(i):
2770 c = str(self.entrycget(i, 'command'))
2771 if c:
2772 self.deletecommand(c)
2773 self.tk.call(self._w, 'delete', index1, index2)
Fredrik Lundh06d28152000-08-09 18:03:12 +00002774 def entrycget(self, index, option):
2775 """Return the resource value of an menu item for OPTION at INDEX."""
2776 return self.tk.call(self._w, 'entrycget', index, '-' + option)
2777 def entryconfigure(self, index, cnf=None, **kw):
2778 """Configure a menu item at INDEX."""
Martin v. Löwis6ce13152002-10-10 14:36:13 +00002779 return self._configure(('entryconfigure', index), cnf, kw)
Fredrik Lundh06d28152000-08-09 18:03:12 +00002780 entryconfig = entryconfigure
2781 def index(self, index):
2782 """Return the index of a menu item identified by INDEX."""
2783 i = self.tk.call(self._w, 'index', index)
2784 if i == 'none': return None
Serhiy Storchaka645058d2015-05-06 14:00:04 +03002785 return self.tk.getint(i)
Fredrik Lundh06d28152000-08-09 18:03:12 +00002786 def invoke(self, index):
2787 """Invoke a menu item identified by INDEX and execute
2788 the associated command."""
2789 return self.tk.call(self._w, 'invoke', index)
2790 def post(self, x, y):
2791 """Display a menu at position X,Y."""
2792 self.tk.call(self._w, 'post', x, y)
2793 def type(self, index):
2794 """Return the type of the menu item at INDEX."""
2795 return self.tk.call(self._w, 'type', index)
2796 def unpost(self):
2797 """Unmap a menu."""
2798 self.tk.call(self._w, 'unpost')
Martin v. Löwis5c3c4242012-03-13 13:40:42 -07002799 def xposition(self, index): # new in Tk 8.5
2800 """Return the x-position of the leftmost pixel of the menu item
2801 at INDEX."""
Serhiy Storchaka645058d2015-05-06 14:00:04 +03002802 return self.tk.getint(self.tk.call(self._w, 'xposition', index))
Fredrik Lundh06d28152000-08-09 18:03:12 +00002803 def yposition(self, index):
2804 """Return the y-position of the topmost pixel of the menu item at INDEX."""
Serhiy Storchaka645058d2015-05-06 14:00:04 +03002805 return self.tk.getint(self.tk.call(
Fredrik Lundh06d28152000-08-09 18:03:12 +00002806 self._w, 'yposition', index))
Guido van Rossum18468821994-06-20 07:49:28 +00002807
2808class Menubutton(Widget):
Fredrik Lundh06d28152000-08-09 18:03:12 +00002809 """Menubutton widget, obsolete since Tk8.0."""
2810 def __init__(self, master=None, cnf={}, **kw):
2811 Widget.__init__(self, master, 'menubutton', cnf, kw)
Guido van Rossum18468821994-06-20 07:49:28 +00002812
2813class Message(Widget):
Fredrik Lundh06d28152000-08-09 18:03:12 +00002814 """Message widget to display multiline text. Obsolete since Label does it too."""
2815 def __init__(self, master=None, cnf={}, **kw):
2816 Widget.__init__(self, master, 'message', cnf, kw)
Guido van Rossum18468821994-06-20 07:49:28 +00002817
2818class Radiobutton(Widget):
Fredrik Lundh06d28152000-08-09 18:03:12 +00002819 """Radiobutton widget which shows only one of several buttons in on-state."""
2820 def __init__(self, master=None, cnf={}, **kw):
2821 """Construct a radiobutton widget with the parent MASTER.
Guido van Rossum5917ecb2000-06-29 16:30:50 +00002822
Fredrik Lundh06d28152000-08-09 18:03:12 +00002823 Valid resource names: activebackground, activeforeground, anchor,
2824 background, bd, bg, bitmap, borderwidth, command, cursor,
2825 disabledforeground, fg, font, foreground, height,
2826 highlightbackground, highlightcolor, highlightthickness, image,
2827 indicatoron, justify, padx, pady, relief, selectcolor, selectimage,
2828 state, takefocus, text, textvariable, underline, value, variable,
2829 width, wraplength."""
2830 Widget.__init__(self, master, 'radiobutton', cnf, kw)
2831 def deselect(self):
2832 """Put the button in off-state."""
Guido van Rossum5917ecb2000-06-29 16:30:50 +00002833
Fredrik Lundh06d28152000-08-09 18:03:12 +00002834 self.tk.call(self._w, 'deselect')
2835 def flash(self):
2836 """Flash the button."""
2837 self.tk.call(self._w, 'flash')
2838 def invoke(self):
2839 """Toggle the button and invoke a command if given as resource."""
2840 return self.tk.call(self._w, 'invoke')
2841 def select(self):
2842 """Put the button in on-state."""
2843 self.tk.call(self._w, 'select')
Guido van Rossum18468821994-06-20 07:49:28 +00002844
2845class Scale(Widget):
Fredrik Lundh06d28152000-08-09 18:03:12 +00002846 """Scale widget which can display a numerical scale."""
2847 def __init__(self, master=None, cnf={}, **kw):
2848 """Construct a scale widget with the parent MASTER.
Guido van Rossum5917ecb2000-06-29 16:30:50 +00002849
Fredrik Lundh06d28152000-08-09 18:03:12 +00002850 Valid resource names: activebackground, background, bigincrement, bd,
2851 bg, borderwidth, command, cursor, digits, fg, font, foreground, from,
2852 highlightbackground, highlightcolor, highlightthickness, label,
2853 length, orient, relief, repeatdelay, repeatinterval, resolution,
2854 showvalue, sliderlength, sliderrelief, state, takefocus,
2855 tickinterval, to, troughcolor, variable, width."""
2856 Widget.__init__(self, master, 'scale', cnf, kw)
2857 def get(self):
2858 """Get the current value as integer or float."""
2859 value = self.tk.call(self._w, 'get')
2860 try:
Serhiy Storchaka645058d2015-05-06 14:00:04 +03002861 return self.tk.getint(value)
2862 except (ValueError, TclError):
2863 return self.tk.getdouble(value)
Fredrik Lundh06d28152000-08-09 18:03:12 +00002864 def set(self, value):
2865 """Set the value to VALUE."""
2866 self.tk.call(self._w, 'set', value)
2867 def coords(self, value=None):
2868 """Return a tuple (X,Y) of the point along the centerline of the
2869 trough that corresponds to VALUE or the current value if None is
2870 given."""
2871
2872 return self._getints(self.tk.call(self._w, 'coords', value))
2873 def identify(self, x, y):
2874 """Return where the point X,Y lies. Valid return values are "slider",
2875 "though1" and "though2"."""
2876 return self.tk.call(self._w, 'identify', x, y)
Guido van Rossum18468821994-06-20 07:49:28 +00002877
2878class Scrollbar(Widget):
Fredrik Lundh06d28152000-08-09 18:03:12 +00002879 """Scrollbar widget which displays a slider at a certain position."""
2880 def __init__(self, master=None, cnf={}, **kw):
2881 """Construct a scrollbar widget with the parent MASTER.
Guido van Rossum5917ecb2000-06-29 16:30:50 +00002882
Fredrik Lundh06d28152000-08-09 18:03:12 +00002883 Valid resource names: activebackground, activerelief,
2884 background, bd, bg, borderwidth, command, cursor,
2885 elementborderwidth, highlightbackground,
2886 highlightcolor, highlightthickness, jump, orient,
2887 relief, repeatdelay, repeatinterval, takefocus,
2888 troughcolor, width."""
2889 Widget.__init__(self, master, 'scrollbar', cnf, kw)
Serhiy Storchaka320f3392014-07-23 22:00:44 +03002890 def activate(self, index=None):
2891 """Marks the element indicated by index as active.
2892 The only index values understood by this method are "arrow1",
2893 "slider", or "arrow2". If any other value is specified then no
2894 element of the scrollbar will be active. If index is not specified,
2895 the method returns the name of the element that is currently active,
2896 or None if no element is active."""
2897 return self.tk.call(self._w, 'activate', index) or None
Fredrik Lundh06d28152000-08-09 18:03:12 +00002898 def delta(self, deltax, deltay):
2899 """Return the fractional change of the scrollbar setting if it
2900 would be moved by DELTAX or DELTAY pixels."""
Serhiy Storchaka645058d2015-05-06 14:00:04 +03002901 return self.tk.getdouble(
Fredrik Lundh06d28152000-08-09 18:03:12 +00002902 self.tk.call(self._w, 'delta', deltax, deltay))
2903 def fraction(self, x, y):
2904 """Return the fractional value which corresponds to a slider
2905 position of X,Y."""
Serhiy Storchaka645058d2015-05-06 14:00:04 +03002906 return self.tk.getdouble(self.tk.call(self._w, 'fraction', x, y))
Fredrik Lundh06d28152000-08-09 18:03:12 +00002907 def identify(self, x, y):
2908 """Return the element under position X,Y as one of
2909 "arrow1","slider","arrow2" or ""."""
2910 return self.tk.call(self._w, 'identify', x, y)
2911 def get(self):
2912 """Return the current fractional values (upper and lower end)
2913 of the slider position."""
2914 return self._getdoubles(self.tk.call(self._w, 'get'))
Serhiy Storchaka320f3392014-07-23 22:00:44 +03002915 def set(self, first, last):
Fredrik Lundh06d28152000-08-09 18:03:12 +00002916 """Set the fractional values of the slider position (upper and
2917 lower ends as value between 0 and 1)."""
Serhiy Storchaka320f3392014-07-23 22:00:44 +03002918 self.tk.call(self._w, 'set', first, last)
Raymond Hettingerff41c482003-04-06 09:01:11 +00002919
2920
2921
Guilherme Polo1fff0082009-08-14 15:05:30 +00002922class Text(Widget, XView, YView):
Fredrik Lundh06d28152000-08-09 18:03:12 +00002923 """Text widget which can display text in various forms."""
Fredrik Lundh06d28152000-08-09 18:03:12 +00002924 def __init__(self, master=None, cnf={}, **kw):
2925 """Construct a text widget with the parent MASTER.
Raymond Hettingerff41c482003-04-06 09:01:11 +00002926
Martin v. Löwis2ec36272002-10-13 10:22:08 +00002927 STANDARD OPTIONS
Raymond Hettingerff41c482003-04-06 09:01:11 +00002928
Martin v. Löwis2ec36272002-10-13 10:22:08 +00002929 background, borderwidth, cursor,
2930 exportselection, font, foreground,
2931 highlightbackground, highlightcolor,
2932 highlightthickness, insertbackground,
2933 insertborderwidth, insertofftime,
2934 insertontime, insertwidth, padx, pady,
Raymond Hettingerff41c482003-04-06 09:01:11 +00002935 relief, selectbackground,
Martin v. Löwis2ec36272002-10-13 10:22:08 +00002936 selectborderwidth, selectforeground,
Raymond Hettingerff41c482003-04-06 09:01:11 +00002937 setgrid, takefocus,
Martin v. Löwis2ec36272002-10-13 10:22:08 +00002938 xscrollcommand, yscrollcommand,
Guido van Rossum5917ecb2000-06-29 16:30:50 +00002939
Martin v. Löwis2ec36272002-10-13 10:22:08 +00002940 WIDGET-SPECIFIC OPTIONS
Raymond Hettingerff41c482003-04-06 09:01:11 +00002941
Martin v. Löwis2ec36272002-10-13 10:22:08 +00002942 autoseparators, height, maxundo,
Raymond Hettingerff41c482003-04-06 09:01:11 +00002943 spacing1, spacing2, spacing3,
Martin v. Löwis2ec36272002-10-13 10:22:08 +00002944 state, tabs, undo, width, wrap,
Raymond Hettingerff41c482003-04-06 09:01:11 +00002945
Martin v. Löwis2ec36272002-10-13 10:22:08 +00002946 """
Fredrik Lundh06d28152000-08-09 18:03:12 +00002947 Widget.__init__(self, master, 'text', cnf, kw)
Serhiy Storchaka4babb912013-11-03 14:34:25 +02002948 def bbox(self, index):
Fredrik Lundh06d28152000-08-09 18:03:12 +00002949 """Return a tuple of (x,y,width,height) which gives the bounding
Serhiy Storchaka4babb912013-11-03 14:34:25 +02002950 box of the visible part of the character at the given index."""
Fredrik Lundh06d28152000-08-09 18:03:12 +00002951 return self._getints(
Serhiy Storchaka4babb912013-11-03 14:34:25 +02002952 self.tk.call(self._w, 'bbox', index)) or None
Fredrik Lundh06d28152000-08-09 18:03:12 +00002953 def compare(self, index1, op, index2):
2954 """Return whether between index INDEX1 and index INDEX2 the
2955 relation OP is satisfied. OP is one of <, <=, ==, >=, >, or !=."""
2956 return self.tk.getboolean(self.tk.call(
2957 self._w, 'compare', index1, op, index2))
Martin v. Löwis5c3c4242012-03-13 13:40:42 -07002958 def count(self, index1, index2, *args): # new in Tk 8.5
2959 """Counts the number of relevant things between the two indices.
2960 If index1 is after index2, the result will be a negative number
2961 (and this holds for each of the possible options).
2962
2963 The actual items which are counted depends on the options given by
2964 args. The result is a list of integers, one for the result of each
2965 counting option given. Valid counting options are "chars",
2966 "displaychars", "displayindices", "displaylines", "indices",
2967 "lines", "xpixels" and "ypixels". There is an additional possible
2968 option "update", which if given then all subsequent options ensure
2969 that any possible out of date information is recalculated."""
2970 args = ['-%s' % arg for arg in args if not arg.startswith('-')]
2971 args += [index1, index2]
2972 res = self.tk.call(self._w, 'count', *args) or None
2973 if res is not None and len(args) <= 3:
2974 return (res, )
2975 else:
2976 return res
Fredrik Lundh06d28152000-08-09 18:03:12 +00002977 def debug(self, boolean=None):
2978 """Turn on the internal consistency checks of the B-Tree inside the text
2979 widget according to BOOLEAN."""
Serhiy Storchaka0b9e8152013-11-03 14:29:35 +02002980 if boolean is None:
Serhiy Storchaka2f26c222014-01-11 13:13:46 +02002981 return self.tk.getboolean(self.tk.call(self._w, 'debug'))
Serhiy Storchaka0b9e8152013-11-03 14:29:35 +02002982 self.tk.call(self._w, 'debug', boolean)
Fredrik Lundh06d28152000-08-09 18:03:12 +00002983 def delete(self, index1, index2=None):
2984 """Delete the characters between INDEX1 and INDEX2 (not included)."""
2985 self.tk.call(self._w, 'delete', index1, index2)
2986 def dlineinfo(self, index):
2987 """Return tuple (x,y,width,height,baseline) giving the bounding box
2988 and baseline position of the visible part of the line containing
2989 the character at INDEX."""
2990 return self._getints(self.tk.call(self._w, 'dlineinfo', index))
Guido van Rossum256705b2002-04-23 13:29:43 +00002991 def dump(self, index1, index2=None, command=None, **kw):
2992 """Return the contents of the widget between index1 and index2.
Raymond Hettingerff41c482003-04-06 09:01:11 +00002993
Guido van Rossum256705b2002-04-23 13:29:43 +00002994 The type of contents returned in filtered based on the keyword
2995 parameters; if 'all', 'image', 'mark', 'tag', 'text', or 'window' are
2996 given and true, then the corresponding items are returned. The result
2997 is a list of triples of the form (key, value, index). If none of the
2998 keywords are true then 'all' is used by default.
Raymond Hettingerff41c482003-04-06 09:01:11 +00002999
Guido van Rossum256705b2002-04-23 13:29:43 +00003000 If the 'command' argument is given, it is called once for each element
3001 of the list of triples, with the values of each triple serving as the
3002 arguments to the function. In this case the list is not returned."""
3003 args = []
3004 func_name = None
3005 result = None
3006 if not command:
3007 # Never call the dump command without the -command flag, since the
3008 # output could involve Tcl quoting and would be a pain to parse
3009 # right. Instead just set the command to build a list of triples
3010 # as if we had done the parsing.
3011 result = []
3012 def append_triple(key, value, index, result=result):
3013 result.append((key, value, index))
3014 command = append_triple
3015 try:
3016 if not isinstance(command, str):
3017 func_name = command = self._register(command)
3018 args += ["-command", command]
3019 for key in kw:
3020 if kw[key]: args.append("-" + key)
3021 args.append(index1)
3022 if index2:
3023 args.append(index2)
3024 self.tk.call(self._w, "dump", *args)
3025 return result
3026 finally:
3027 if func_name:
3028 self.deletecommand(func_name)
Raymond Hettingerff41c482003-04-06 09:01:11 +00003029
Martin v. Löwis2ec36272002-10-13 10:22:08 +00003030 ## new in tk8.4
3031 def edit(self, *args):
3032 """Internal method
Raymond Hettingerff41c482003-04-06 09:01:11 +00003033
3034 This method controls the undo mechanism and
3035 the modified flag. The exact behavior of the
3036 command depends on the option argument that
3037 follows the edit argument. The following forms
Martin v. Löwis2ec36272002-10-13 10:22:08 +00003038 of the command are currently supported:
Raymond Hettingerff41c482003-04-06 09:01:11 +00003039
Martin v. Löwis2ec36272002-10-13 10:22:08 +00003040 edit_modified, edit_redo, edit_reset, edit_separator
3041 and edit_undo
Raymond Hettingerff41c482003-04-06 09:01:11 +00003042
Martin v. Löwis2ec36272002-10-13 10:22:08 +00003043 """
Georg Brandlb533e262008-05-25 18:19:30 +00003044 return self.tk.call(self._w, 'edit', *args)
Martin v. Löwis2ec36272002-10-13 10:22:08 +00003045
3046 def edit_modified(self, arg=None):
3047 """Get or Set the modified flag
Raymond Hettingerff41c482003-04-06 09:01:11 +00003048
Martin v. Löwis2ec36272002-10-13 10:22:08 +00003049 If arg is not specified, returns the modified
Raymond Hettingerff41c482003-04-06 09:01:11 +00003050 flag of the widget. The insert, delete, edit undo and
3051 edit redo commands or the user can set or clear the
3052 modified flag. If boolean is specified, sets the
Martin v. Löwis2ec36272002-10-13 10:22:08 +00003053 modified flag of the widget to arg.
3054 """
3055 return self.edit("modified", arg)
Raymond Hettingerff41c482003-04-06 09:01:11 +00003056
Martin v. Löwis2ec36272002-10-13 10:22:08 +00003057 def edit_redo(self):
3058 """Redo the last undone edit
Raymond Hettingerff41c482003-04-06 09:01:11 +00003059
3060 When the undo option is true, reapplies the last
3061 undone edits provided no other edits were done since
Martin v. Löwis2ec36272002-10-13 10:22:08 +00003062 then. Generates an error when the redo stack is empty.
3063 Does nothing when the undo option is false.
3064 """
3065 return self.edit("redo")
Raymond Hettingerff41c482003-04-06 09:01:11 +00003066
Martin v. Löwis2ec36272002-10-13 10:22:08 +00003067 def edit_reset(self):
3068 """Clears the undo and redo stacks
3069 """
3070 return self.edit("reset")
Raymond Hettingerff41c482003-04-06 09:01:11 +00003071
Martin v. Löwis2ec36272002-10-13 10:22:08 +00003072 def edit_separator(self):
Raymond Hettingerff41c482003-04-06 09:01:11 +00003073 """Inserts a separator (boundary) on the undo stack.
3074
Martin v. Löwis2ec36272002-10-13 10:22:08 +00003075 Does nothing when the undo option is false
3076 """
3077 return self.edit("separator")
Raymond Hettingerff41c482003-04-06 09:01:11 +00003078
Martin v. Löwis2ec36272002-10-13 10:22:08 +00003079 def edit_undo(self):
Raymond Hettingerff41c482003-04-06 09:01:11 +00003080 """Undoes the last edit action
3081
3082 If the undo option is true. An edit action is defined
3083 as all the insert and delete commands that are recorded
3084 on the undo stack in between two separators. Generates
3085 an error when the undo stack is empty. Does nothing
Martin v. Löwis2ec36272002-10-13 10:22:08 +00003086 when the undo option is false
3087 """
3088 return self.edit("undo")
Raymond Hettingerff41c482003-04-06 09:01:11 +00003089
Fredrik Lundh06d28152000-08-09 18:03:12 +00003090 def get(self, index1, index2=None):
3091 """Return the text from INDEX1 to INDEX2 (not included)."""
3092 return self.tk.call(self._w, 'get', index1, index2)
3093 # (Image commands are new in 8.0)
3094 def image_cget(self, index, option):
3095 """Return the value of OPTION of an embedded image at INDEX."""
3096 if option[:1] != "-":
3097 option = "-" + option
3098 if option[-1:] == "_":
3099 option = option[:-1]
3100 return self.tk.call(self._w, "image", "cget", index, option)
Martin v. Löwis6ce13152002-10-10 14:36:13 +00003101 def image_configure(self, index, cnf=None, **kw):
Fredrik Lundh06d28152000-08-09 18:03:12 +00003102 """Configure an embedded image at INDEX."""
Martin v. Löwis6ce13152002-10-10 14:36:13 +00003103 return self._configure(('image', 'configure', index), cnf, kw)
Fredrik Lundh06d28152000-08-09 18:03:12 +00003104 def image_create(self, index, cnf={}, **kw):
3105 """Create an embedded image at INDEX."""
Raymond Hettingerff41c482003-04-06 09:01:11 +00003106 return self.tk.call(
3107 self._w, "image", "create", index,
3108 *self._options(cnf, kw))
Fredrik Lundh06d28152000-08-09 18:03:12 +00003109 def image_names(self):
3110 """Return all names of embedded images in this widget."""
3111 return self.tk.call(self._w, "image", "names")
3112 def index(self, index):
3113 """Return the index in the form line.char for INDEX."""
Christian Heimes57dddfb2008-01-02 18:30:52 +00003114 return str(self.tk.call(self._w, 'index', index))
Fredrik Lundh06d28152000-08-09 18:03:12 +00003115 def insert(self, index, chars, *args):
3116 """Insert CHARS before the characters at INDEX. An additional
3117 tag can be given in ARGS. Additional CHARS and tags can follow in ARGS."""
3118 self.tk.call((self._w, 'insert', index, chars) + args)
3119 def mark_gravity(self, markName, direction=None):
3120 """Change the gravity of a mark MARKNAME to DIRECTION (LEFT or RIGHT).
3121 Return the current value if None is given for DIRECTION."""
3122 return self.tk.call(
3123 (self._w, 'mark', 'gravity', markName, direction))
3124 def mark_names(self):
3125 """Return all mark names."""
3126 return self.tk.splitlist(self.tk.call(
3127 self._w, 'mark', 'names'))
3128 def mark_set(self, markName, index):
3129 """Set mark MARKNAME before the character at INDEX."""
3130 self.tk.call(self._w, 'mark', 'set', markName, index)
3131 def mark_unset(self, *markNames):
3132 """Delete all marks in MARKNAMES."""
3133 self.tk.call((self._w, 'mark', 'unset') + markNames)
3134 def mark_next(self, index):
3135 """Return the name of the next mark after INDEX."""
3136 return self.tk.call(self._w, 'mark', 'next', index) or None
3137 def mark_previous(self, index):
3138 """Return the name of the previous mark before INDEX."""
3139 return self.tk.call(self._w, 'mark', 'previous', index) or None
Martin v. Löwis5c3c4242012-03-13 13:40:42 -07003140 def peer_create(self, newPathName, cnf={}, **kw): # new in Tk 8.5
3141 """Creates a peer text widget with the given newPathName, and any
3142 optional standard configuration options. By default the peer will
Terry Jan Reedy0f847642013-03-11 18:34:00 -04003143 have the same start and end line as the parent widget, but
Martin v. Löwis5c3c4242012-03-13 13:40:42 -07003144 these can be overriden with the standard configuration options."""
3145 self.tk.call(self._w, 'peer', 'create', newPathName,
3146 *self._options(cnf, kw))
3147 def peer_names(self): # new in Tk 8.5
3148 """Returns a list of peers of this widget (this does not include
3149 the widget itself)."""
3150 return self.tk.splitlist(self.tk.call(self._w, 'peer', 'names'))
3151 def replace(self, index1, index2, chars, *args): # new in Tk 8.5
3152 """Replaces the range of characters between index1 and index2 with
3153 the given characters and tags specified by args.
3154
3155 See the method insert for some more information about args, and the
3156 method delete for information about the indices."""
3157 self.tk.call(self._w, 'replace', index1, index2, chars, *args)
Fredrik Lundh06d28152000-08-09 18:03:12 +00003158 def scan_mark(self, x, y):
3159 """Remember the current X, Y coordinates."""
3160 self.tk.call(self._w, 'scan', 'mark', x, y)
3161 def scan_dragto(self, x, y):
3162 """Adjust the view of the text to 10 times the
3163 difference between X and Y and the coordinates given in
3164 scan_mark."""
3165 self.tk.call(self._w, 'scan', 'dragto', x, y)
3166 def search(self, pattern, index, stopindex=None,
3167 forwards=None, backwards=None, exact=None,
Thomas Wouters89f507f2006-12-13 04:49:30 +00003168 regexp=None, nocase=None, count=None, elide=None):
Fredrik Lundh06d28152000-08-09 18:03:12 +00003169 """Search PATTERN beginning from INDEX until STOPINDEX.
Guilherme Poloae098992009-02-09 16:44:24 +00003170 Return the index of the first character of a match or an
3171 empty string."""
Fredrik Lundh06d28152000-08-09 18:03:12 +00003172 args = [self._w, 'search']
3173 if forwards: args.append('-forwards')
3174 if backwards: args.append('-backwards')
3175 if exact: args.append('-exact')
3176 if regexp: args.append('-regexp')
3177 if nocase: args.append('-nocase')
Thomas Wouters89f507f2006-12-13 04:49:30 +00003178 if elide: args.append('-elide')
Fredrik Lundh06d28152000-08-09 18:03:12 +00003179 if count: args.append('-count'); args.append(count)
Guilherme Poloae098992009-02-09 16:44:24 +00003180 if pattern and pattern[0] == '-': args.append('--')
Fredrik Lundh06d28152000-08-09 18:03:12 +00003181 args.append(pattern)
3182 args.append(index)
3183 if stopindex: args.append(stopindex)
Guilherme Polo56f5be52009-03-07 01:54:57 +00003184 return str(self.tk.call(tuple(args)))
Fredrik Lundh06d28152000-08-09 18:03:12 +00003185 def see(self, index):
3186 """Scroll such that the character at INDEX is visible."""
3187 self.tk.call(self._w, 'see', index)
3188 def tag_add(self, tagName, index1, *args):
3189 """Add tag TAGNAME to all characters between INDEX1 and index2 in ARGS.
3190 Additional pairs of indices may follow in ARGS."""
3191 self.tk.call(
3192 (self._w, 'tag', 'add', tagName, index1) + args)
3193 def tag_unbind(self, tagName, sequence, funcid=None):
3194 """Unbind for all characters with TAGNAME for event SEQUENCE the
3195 function identified with FUNCID."""
3196 self.tk.call(self._w, 'tag', 'bind', tagName, sequence, '')
3197 if funcid:
3198 self.deletecommand(funcid)
3199 def tag_bind(self, tagName, sequence, func, add=None):
3200 """Bind to all characters with TAGNAME at event SEQUENCE a call to function FUNC.
Guido van Rossum5917ecb2000-06-29 16:30:50 +00003201
Fredrik Lundh06d28152000-08-09 18:03:12 +00003202 An additional boolean parameter ADD specifies whether FUNC will be
3203 called additionally to the other bound function or whether it will
3204 replace the previous function. See bind for the return value."""
3205 return self._bind((self._w, 'tag', 'bind', tagName),
3206 sequence, func, add)
3207 def tag_cget(self, tagName, option):
3208 """Return the value of OPTION for tag TAGNAME."""
3209 if option[:1] != '-':
3210 option = '-' + option
3211 if option[-1:] == '_':
3212 option = option[:-1]
3213 return self.tk.call(self._w, 'tag', 'cget', tagName, option)
Martin v. Löwis6ce13152002-10-10 14:36:13 +00003214 def tag_configure(self, tagName, cnf=None, **kw):
Fredrik Lundh06d28152000-08-09 18:03:12 +00003215 """Configure a tag TAGNAME."""
Martin v. Löwis6ce13152002-10-10 14:36:13 +00003216 return self._configure(('tag', 'configure', tagName), cnf, kw)
Fredrik Lundh06d28152000-08-09 18:03:12 +00003217 tag_config = tag_configure
3218 def tag_delete(self, *tagNames):
3219 """Delete all tags in TAGNAMES."""
3220 self.tk.call((self._w, 'tag', 'delete') + tagNames)
3221 def tag_lower(self, tagName, belowThis=None):
3222 """Change the priority of tag TAGNAME such that it is lower
3223 than the priority of BELOWTHIS."""
3224 self.tk.call(self._w, 'tag', 'lower', tagName, belowThis)
3225 def tag_names(self, index=None):
3226 """Return a list of all tag names."""
3227 return self.tk.splitlist(
3228 self.tk.call(self._w, 'tag', 'names', index))
3229 def tag_nextrange(self, tagName, index1, index2=None):
3230 """Return a list of start and end index for the first sequence of
3231 characters between INDEX1 and INDEX2 which all have tag TAGNAME.
3232 The text is searched forward from INDEX1."""
3233 return self.tk.splitlist(self.tk.call(
3234 self._w, 'tag', 'nextrange', tagName, index1, index2))
3235 def tag_prevrange(self, tagName, index1, index2=None):
3236 """Return a list of start and end index for the first sequence of
3237 characters between INDEX1 and INDEX2 which all have tag TAGNAME.
3238 The text is searched backwards from INDEX1."""
3239 return self.tk.splitlist(self.tk.call(
3240 self._w, 'tag', 'prevrange', tagName, index1, index2))
3241 def tag_raise(self, tagName, aboveThis=None):
3242 """Change the priority of tag TAGNAME such that it is higher
3243 than the priority of ABOVETHIS."""
3244 self.tk.call(
3245 self._w, 'tag', 'raise', tagName, aboveThis)
3246 def tag_ranges(self, tagName):
3247 """Return a list of ranges of text which have tag TAGNAME."""
3248 return self.tk.splitlist(self.tk.call(
3249 self._w, 'tag', 'ranges', tagName))
3250 def tag_remove(self, tagName, index1, index2=None):
3251 """Remove tag TAGNAME from all characters between INDEX1 and INDEX2."""
3252 self.tk.call(
3253 self._w, 'tag', 'remove', tagName, index1, index2)
3254 def window_cget(self, index, option):
3255 """Return the value of OPTION of an embedded window at INDEX."""
3256 if option[:1] != '-':
3257 option = '-' + option
3258 if option[-1:] == '_':
3259 option = option[:-1]
3260 return self.tk.call(self._w, 'window', 'cget', index, option)
Martin v. Löwis6ce13152002-10-10 14:36:13 +00003261 def window_configure(self, index, cnf=None, **kw):
Fredrik Lundh06d28152000-08-09 18:03:12 +00003262 """Configure an embedded window at INDEX."""
Martin v. Löwis6ce13152002-10-10 14:36:13 +00003263 return self._configure(('window', 'configure', index), cnf, kw)
Fredrik Lundh06d28152000-08-09 18:03:12 +00003264 window_config = window_configure
3265 def window_create(self, index, cnf={}, **kw):
3266 """Create a window at INDEX."""
3267 self.tk.call(
3268 (self._w, 'window', 'create', index)
3269 + self._options(cnf, kw))
3270 def window_names(self):
3271 """Return all names of embedded windows in this widget."""
3272 return self.tk.splitlist(
3273 self.tk.call(self._w, 'window', 'names'))
Fredrik Lundh06d28152000-08-09 18:03:12 +00003274 def yview_pickplace(self, *what):
3275 """Obsolete function, use see."""
3276 self.tk.call((self._w, 'yview', '-pickplace') + what)
Guido van Rossum18468821994-06-20 07:49:28 +00003277
Martin v. Löwis2ec36272002-10-13 10:22:08 +00003278
Guido van Rossum28574b51996-10-21 15:16:51 +00003279class _setit:
Fredrik Lundh06d28152000-08-09 18:03:12 +00003280 """Internal class. It wraps the command in the widget OptionMenu."""
3281 def __init__(self, var, value, callback=None):
3282 self.__value = value
3283 self.__var = var
3284 self.__callback = callback
3285 def __call__(self, *args):
3286 self.__var.set(self.__value)
3287 if self.__callback:
Raymond Hettingerff41c482003-04-06 09:01:11 +00003288 self.__callback(self.__value, *args)
Guido van Rossum28574b51996-10-21 15:16:51 +00003289
3290class OptionMenu(Menubutton):
Fredrik Lundh06d28152000-08-09 18:03:12 +00003291 """OptionMenu which allows the user to select a value from a menu."""
3292 def __init__(self, master, variable, value, *values, **kwargs):
3293 """Construct an optionmenu widget with the parent MASTER, with
3294 the resource textvariable set to VARIABLE, the initially selected
3295 value VALUE, the other menu values VALUES and an additional
3296 keyword argument command."""
3297 kw = {"borderwidth": 2, "textvariable": variable,
3298 "indicatoron": 1, "relief": RAISED, "anchor": "c",
3299 "highlightthickness": 2}
3300 Widget.__init__(self, master, "menubutton", kw)
3301 self.widgetName = 'tk_optionMenu'
3302 menu = self.__menu = Menu(self, name="menu", tearoff=0)
3303 self.menuname = menu._w
3304 # 'command' is the only supported keyword
3305 callback = kwargs.get('command')
Guido van Rossume014a132006-08-19 16:53:45 +00003306 if 'command' in kwargs:
Fredrik Lundh06d28152000-08-09 18:03:12 +00003307 del kwargs['command']
3308 if kwargs:
Collin Winterce36ad82007-08-30 01:19:48 +00003309 raise TclError('unknown option -'+kwargs.keys()[0])
Fredrik Lundh06d28152000-08-09 18:03:12 +00003310 menu.add_command(label=value,
3311 command=_setit(variable, value, callback))
3312 for v in values:
3313 menu.add_command(label=v,
3314 command=_setit(variable, v, callback))
3315 self["menu"] = menu
Guido van Rossum28574b51996-10-21 15:16:51 +00003316
Fredrik Lundh06d28152000-08-09 18:03:12 +00003317 def __getitem__(self, name):
3318 if name == 'menu':
3319 return self.__menu
3320 return Widget.__getitem__(self, name)
Guido van Rossum28574b51996-10-21 15:16:51 +00003321
Fredrik Lundh06d28152000-08-09 18:03:12 +00003322 def destroy(self):
3323 """Destroy this widget and the associated menu."""
3324 Menubutton.destroy(self)
3325 self.__menu = None
Guido van Rossumbf4d8f91995-09-01 20:35:37 +00003326
Guido van Rossum35f67fb1995-08-04 03:50:29 +00003327class Image:
Fredrik Lundh06d28152000-08-09 18:03:12 +00003328 """Base class for images."""
Martin v. Löwis0d8ce612000-09-08 16:28:30 +00003329 _last_id = 0
Fredrik Lundh06d28152000-08-09 18:03:12 +00003330 def __init__(self, imgtype, name=None, cnf={}, master=None, **kw):
3331 self.name = None
3332 if not master:
3333 master = _default_root
3334 if not master:
Collin Winterce36ad82007-08-30 01:19:48 +00003335 raise RuntimeError('Too early to create image')
Serhiy Storchakad00aff22014-08-24 09:07:47 +03003336 self.tk = getattr(master, 'tk', master)
Fredrik Lundh06d28152000-08-09 18:03:12 +00003337 if not name:
Martin v. Löwis0d8ce612000-09-08 16:28:30 +00003338 Image._last_id += 1
Walter Dörwald70a6b492004-02-12 17:35:32 +00003339 name = "pyimage%r" % (Image._last_id,) # tk itself would use image<x>
Fredrik Lundh06d28152000-08-09 18:03:12 +00003340 # The following is needed for systems where id(x)
3341 # can return a negative number, such as Linux/m68k:
3342 if name[0] == '-': name = '_' + name[1:]
3343 if kw and cnf: cnf = _cnfmerge((cnf, kw))
3344 elif kw: cnf = kw
3345 options = ()
3346 for k, v in cnf.items():
Florent Xicluna5d1155c2011-10-28 14:45:05 +02003347 if callable(v):
Fredrik Lundh06d28152000-08-09 18:03:12 +00003348 v = self._register(v)
3349 options = options + ('-'+k, v)
3350 self.tk.call(('image', 'create', imgtype, name,) + options)
3351 self.name = name
3352 def __str__(self): return self.name
3353 def __del__(self):
3354 if self.name:
3355 try:
3356 self.tk.call('image', 'delete', self.name)
3357 except TclError:
3358 # May happen if the root was destroyed
3359 pass
3360 def __setitem__(self, key, value):
3361 self.tk.call(self.name, 'configure', '-'+key, value)
3362 def __getitem__(self, key):
3363 return self.tk.call(self.name, 'configure', '-'+key)
3364 def configure(self, **kw):
3365 """Configure the image."""
3366 res = ()
3367 for k, v in _cnfmerge(kw).items():
3368 if v is not None:
3369 if k[-1] == '_': k = k[:-1]
Florent Xicluna5d1155c2011-10-28 14:45:05 +02003370 if callable(v):
Fredrik Lundh06d28152000-08-09 18:03:12 +00003371 v = self._register(v)
3372 res = res + ('-'+k, v)
3373 self.tk.call((self.name, 'config') + res)
3374 config = configure
3375 def height(self):
3376 """Return the height of the image."""
Serhiy Storchaka645058d2015-05-06 14:00:04 +03003377 return self.tk.getint(
Fredrik Lundh06d28152000-08-09 18:03:12 +00003378 self.tk.call('image', 'height', self.name))
3379 def type(self):
3380 """Return the type of the imgage, e.g. "photo" or "bitmap"."""
3381 return self.tk.call('image', 'type', self.name)
3382 def width(self):
3383 """Return the width of the image."""
Serhiy Storchaka645058d2015-05-06 14:00:04 +03003384 return self.tk.getint(
Fredrik Lundh06d28152000-08-09 18:03:12 +00003385 self.tk.call('image', 'width', self.name))
Guido van Rossum35f67fb1995-08-04 03:50:29 +00003386
3387class PhotoImage(Image):
Fredrik Lundh06d28152000-08-09 18:03:12 +00003388 """Widget which can display colored images in GIF, PPM/PGM format."""
3389 def __init__(self, name=None, cnf={}, master=None, **kw):
3390 """Create an image with NAME.
Guido van Rossum5917ecb2000-06-29 16:30:50 +00003391
Fredrik Lundh06d28152000-08-09 18:03:12 +00003392 Valid resource names: data, format, file, gamma, height, palette,
3393 width."""
Raymond Hettingerff41c482003-04-06 09:01:11 +00003394 Image.__init__(self, 'photo', name, cnf, master, **kw)
Fredrik Lundh06d28152000-08-09 18:03:12 +00003395 def blank(self):
3396 """Display a transparent image."""
3397 self.tk.call(self.name, 'blank')
3398 def cget(self, option):
3399 """Return the value of OPTION."""
3400 return self.tk.call(self.name, 'cget', '-' + option)
3401 # XXX config
3402 def __getitem__(self, key):
3403 return self.tk.call(self.name, 'cget', '-' + key)
3404 # XXX copy -from, -to, ...?
3405 def copy(self):
3406 """Return a new PhotoImage with the same image as this widget."""
Serhiy Storchakad00aff22014-08-24 09:07:47 +03003407 destImage = PhotoImage(master=self.tk)
Fredrik Lundh06d28152000-08-09 18:03:12 +00003408 self.tk.call(destImage, 'copy', self.name)
3409 return destImage
Terry Jan Reedyca0250a2016-03-11 15:30:35 -05003410 def zoom(self, x, y=''):
Fredrik Lundh06d28152000-08-09 18:03:12 +00003411 """Return a new PhotoImage with the same image as this widget
Terry Jan Reedyca0250a2016-03-11 15:30:35 -05003412 but zoom it with a factor of x in the X direction and y in the Y
3413 direction. If y is not given, the default value is the same as x.
3414 """
Serhiy Storchakad00aff22014-08-24 09:07:47 +03003415 destImage = PhotoImage(master=self.tk)
Fredrik Lundh06d28152000-08-09 18:03:12 +00003416 if y=='': y=x
3417 self.tk.call(destImage, 'copy', self.name, '-zoom',x,y)
3418 return destImage
Terry Jan Reedyca0250a2016-03-11 15:30:35 -05003419 def subsample(self, x, y=''):
Fredrik Lundh06d28152000-08-09 18:03:12 +00003420 """Return a new PhotoImage based on the same image as this widget
Terry Jan Reedyca0250a2016-03-11 15:30:35 -05003421 but use only every Xth or Yth pixel. If y is not given, the
3422 default value is the same as x.
3423 """
Serhiy Storchakad00aff22014-08-24 09:07:47 +03003424 destImage = PhotoImage(master=self.tk)
Fredrik Lundh06d28152000-08-09 18:03:12 +00003425 if y=='': y=x
3426 self.tk.call(destImage, 'copy', self.name, '-subsample',x,y)
3427 return destImage
3428 def get(self, x, y):
3429 """Return the color (red, green, blue) of the pixel at X,Y."""
3430 return self.tk.call(self.name, 'get', x, y)
3431 def put(self, data, to=None):
Mark Dickinson934896d2009-02-21 20:59:32 +00003432 """Put row formatted colors to image starting from
Fredrik Lundh06d28152000-08-09 18:03:12 +00003433 position TO, e.g. image.put("{red green} {blue yellow}", to=(4,6))"""
3434 args = (self.name, 'put', data)
3435 if to:
3436 if to[0] == '-to':
3437 to = to[1:]
3438 args = args + ('-to',) + tuple(to)
3439 self.tk.call(args)
3440 # XXX read
3441 def write(self, filename, format=None, from_coords=None):
3442 """Write image to file FILENAME in FORMAT starting from
3443 position FROM_COORDS."""
3444 args = (self.name, 'write', filename)
3445 if format:
3446 args = args + ('-format', format)
3447 if from_coords:
3448 args = args + ('-from',) + tuple(from_coords)
3449 self.tk.call(args)
Guido van Rossum35f67fb1995-08-04 03:50:29 +00003450
3451class BitmapImage(Image):
Fredrik Lundh06d28152000-08-09 18:03:12 +00003452 """Widget which can display a bitmap."""
3453 def __init__(self, name=None, cnf={}, master=None, **kw):
3454 """Create a bitmap with NAME.
Guido van Rossum5917ecb2000-06-29 16:30:50 +00003455
Fredrik Lundh06d28152000-08-09 18:03:12 +00003456 Valid resource names: background, data, file, foreground, maskdata, maskfile."""
Raymond Hettingerff41c482003-04-06 09:01:11 +00003457 Image.__init__(self, 'bitmap', name, cnf, master, **kw)
Guido van Rossum35f67fb1995-08-04 03:50:29 +00003458
Serhiy Storchakaa21acb52014-01-07 19:27:42 +02003459def image_names():
3460 return _default_root.tk.splitlist(_default_root.tk.call('image', 'names'))
3461
3462def image_types():
3463 return _default_root.tk.splitlist(_default_root.tk.call('image', 'types'))
Guido van Rossum35f67fb1995-08-04 03:50:29 +00003464
Martin v. Löwis2ec36272002-10-13 10:22:08 +00003465
Guilherme Polo1fff0082009-08-14 15:05:30 +00003466class Spinbox(Widget, XView):
Martin v. Löwis2ec36272002-10-13 10:22:08 +00003467 """spinbox widget."""
3468 def __init__(self, master=None, cnf={}, **kw):
3469 """Construct a spinbox widget with the parent MASTER.
Raymond Hettingerff41c482003-04-06 09:01:11 +00003470
Martin v. Löwis2ec36272002-10-13 10:22:08 +00003471 STANDARD OPTIONS
Raymond Hettingerff41c482003-04-06 09:01:11 +00003472
Martin v. Löwis2ec36272002-10-13 10:22:08 +00003473 activebackground, background, borderwidth,
3474 cursor, exportselection, font, foreground,
3475 highlightbackground, highlightcolor,
3476 highlightthickness, insertbackground,
3477 insertborderwidth, insertofftime,
Raymond Hettingerff41c482003-04-06 09:01:11 +00003478 insertontime, insertwidth, justify, relief,
3479 repeatdelay, repeatinterval,
Martin v. Löwis2ec36272002-10-13 10:22:08 +00003480 selectbackground, selectborderwidth
3481 selectforeground, takefocus, textvariable
3482 xscrollcommand.
Raymond Hettingerff41c482003-04-06 09:01:11 +00003483
Martin v. Löwis2ec36272002-10-13 10:22:08 +00003484 WIDGET-SPECIFIC OPTIONS
Raymond Hettingerff41c482003-04-06 09:01:11 +00003485
3486 buttonbackground, buttoncursor,
3487 buttondownrelief, buttonuprelief,
3488 command, disabledbackground,
3489 disabledforeground, format, from,
3490 invalidcommand, increment,
3491 readonlybackground, state, to,
Martin v. Löwis2ec36272002-10-13 10:22:08 +00003492 validate, validatecommand values,
3493 width, wrap,
3494 """
3495 Widget.__init__(self, master, 'spinbox', cnf, kw)
Raymond Hettingerff41c482003-04-06 09:01:11 +00003496
Martin v. Löwis2ec36272002-10-13 10:22:08 +00003497 def bbox(self, index):
Raymond Hettingerff41c482003-04-06 09:01:11 +00003498 """Return a tuple of X1,Y1,X2,Y2 coordinates for a
3499 rectangle which encloses the character given by index.
3500
3501 The first two elements of the list give the x and y
3502 coordinates of the upper-left corner of the screen
3503 area covered by the character (in pixels relative
3504 to the widget) and the last two elements give the
3505 width and height of the character, in pixels. The
3506 bounding box may refer to a region outside the
Martin v. Löwis2ec36272002-10-13 10:22:08 +00003507 visible area of the window.
3508 """
Serhiy Storchaka2849e0d2013-11-03 14:13:34 +02003509 return self._getints(self.tk.call(self._w, 'bbox', index)) or None
Raymond Hettingerff41c482003-04-06 09:01:11 +00003510
Martin v. Löwis2ec36272002-10-13 10:22:08 +00003511 def delete(self, first, last=None):
3512 """Delete one or more elements of the spinbox.
Raymond Hettingerff41c482003-04-06 09:01:11 +00003513
3514 First is the index of the first character to delete,
3515 and last is the index of the character just after
3516 the last one to delete. If last isn't specified it
3517 defaults to first+1, i.e. a single character is
Martin v. Löwis2ec36272002-10-13 10:22:08 +00003518 deleted. This command returns an empty string.
3519 """
3520 return self.tk.call(self._w, 'delete', first, last)
Raymond Hettingerff41c482003-04-06 09:01:11 +00003521
Martin v. Löwis2ec36272002-10-13 10:22:08 +00003522 def get(self):
3523 """Returns the spinbox's string"""
3524 return self.tk.call(self._w, 'get')
Raymond Hettingerff41c482003-04-06 09:01:11 +00003525
Martin v. Löwis2ec36272002-10-13 10:22:08 +00003526 def icursor(self, index):
3527 """Alter the position of the insertion cursor.
Raymond Hettingerff41c482003-04-06 09:01:11 +00003528
3529 The insertion cursor will be displayed just before
Martin v. Löwis2ec36272002-10-13 10:22:08 +00003530 the character given by index. Returns an empty string
3531 """
3532 return self.tk.call(self._w, 'icursor', index)
Raymond Hettingerff41c482003-04-06 09:01:11 +00003533
Martin v. Löwis2ec36272002-10-13 10:22:08 +00003534 def identify(self, x, y):
Raymond Hettingerff41c482003-04-06 09:01:11 +00003535 """Returns the name of the widget at position x, y
3536
Martin v. Löwis2ec36272002-10-13 10:22:08 +00003537 Return value is one of: none, buttondown, buttonup, entry
3538 """
3539 return self.tk.call(self._w, 'identify', x, y)
Raymond Hettingerff41c482003-04-06 09:01:11 +00003540
Martin v. Löwis2ec36272002-10-13 10:22:08 +00003541 def index(self, index):
3542 """Returns the numerical index corresponding to index
3543 """
3544 return self.tk.call(self._w, 'index', index)
Raymond Hettingerff41c482003-04-06 09:01:11 +00003545
Martin v. Löwis2ec36272002-10-13 10:22:08 +00003546 def insert(self, index, s):
Raymond Hettingerff41c482003-04-06 09:01:11 +00003547 """Insert string s at index
3548
Martin v. Löwis2ec36272002-10-13 10:22:08 +00003549 Returns an empty string.
3550 """
3551 return self.tk.call(self._w, 'insert', index, s)
Raymond Hettingerff41c482003-04-06 09:01:11 +00003552
Martin v. Löwis2ec36272002-10-13 10:22:08 +00003553 def invoke(self, element):
3554 """Causes the specified element to be invoked
Raymond Hettingerff41c482003-04-06 09:01:11 +00003555
Martin v. Löwis2ec36272002-10-13 10:22:08 +00003556 The element could be buttondown or buttonup
3557 triggering the action associated with it.
3558 """
3559 return self.tk.call(self._w, 'invoke', element)
Raymond Hettingerff41c482003-04-06 09:01:11 +00003560
Martin v. Löwis2ec36272002-10-13 10:22:08 +00003561 def scan(self, *args):
3562 """Internal function."""
3563 return self._getints(
3564 self.tk.call((self._w, 'scan') + args)) or ()
Raymond Hettingerff41c482003-04-06 09:01:11 +00003565
Martin v. Löwis2ec36272002-10-13 10:22:08 +00003566 def scan_mark(self, x):
Raymond Hettingerff41c482003-04-06 09:01:11 +00003567 """Records x and the current view in the spinbox window;
3568
3569 used in conjunction with later scan dragto commands.
3570 Typically this command is associated with a mouse button
Martin v. Löwis2ec36272002-10-13 10:22:08 +00003571 press in the widget. It returns an empty string.
3572 """
3573 return self.scan("mark", x)
Raymond Hettingerff41c482003-04-06 09:01:11 +00003574
Martin v. Löwis2ec36272002-10-13 10:22:08 +00003575 def scan_dragto(self, x):
Raymond Hettingerff41c482003-04-06 09:01:11 +00003576 """Compute the difference between the given x argument
Martin v. Löwis2ec36272002-10-13 10:22:08 +00003577 and the x argument to the last scan mark command
Raymond Hettingerff41c482003-04-06 09:01:11 +00003578
3579 It then adjusts the view left or right by 10 times the
3580 difference in x-coordinates. This command is typically
3581 associated with mouse motion events in the widget, to
Martin v. Löwis2ec36272002-10-13 10:22:08 +00003582 produce the effect of dragging the spinbox at high speed
3583 through the window. The return value is an empty string.
3584 """
3585 return self.scan("dragto", x)
Raymond Hettingerff41c482003-04-06 09:01:11 +00003586
Martin v. Löwis2ec36272002-10-13 10:22:08 +00003587 def selection(self, *args):
3588 """Internal function."""
3589 return self._getints(
3590 self.tk.call((self._w, 'selection') + args)) or ()
Raymond Hettingerff41c482003-04-06 09:01:11 +00003591
Martin v. Löwis2ec36272002-10-13 10:22:08 +00003592 def selection_adjust(self, index):
3593 """Locate the end of the selection nearest to the character
Raymond Hettingerff41c482003-04-06 09:01:11 +00003594 given by index,
3595
3596 Then adjust that end of the selection to be at index
3597 (i.e including but not going beyond index). The other
Martin v. Löwis2ec36272002-10-13 10:22:08 +00003598 end of the selection is made the anchor point for future
Raymond Hettingerff41c482003-04-06 09:01:11 +00003599 select to commands. If the selection isn't currently in
3600 the spinbox, then a new selection is created to include
3601 the characters between index and the most recent selection
Martin v. Löwis2ec36272002-10-13 10:22:08 +00003602 anchor point, inclusive. Returns an empty string.
3603 """
3604 return self.selection("adjust", index)
Raymond Hettingerff41c482003-04-06 09:01:11 +00003605
Martin v. Löwis2ec36272002-10-13 10:22:08 +00003606 def selection_clear(self):
Raymond Hettingerff41c482003-04-06 09:01:11 +00003607 """Clear the selection
3608
3609 If the selection isn't in this widget then the
Martin v. Löwis2ec36272002-10-13 10:22:08 +00003610 command has no effect. Returns an empty string.
3611 """
3612 return self.selection("clear")
Raymond Hettingerff41c482003-04-06 09:01:11 +00003613
Martin v. Löwis2ec36272002-10-13 10:22:08 +00003614 def selection_element(self, element=None):
Raymond Hettingerff41c482003-04-06 09:01:11 +00003615 """Sets or gets the currently selected element.
3616
3617 If a spinbutton element is specified, it will be
Martin v. Löwis2ec36272002-10-13 10:22:08 +00003618 displayed depressed
3619 """
3620 return self.selection("element", element)
3621
3622###########################################################################
3623
3624class LabelFrame(Widget):
3625 """labelframe widget."""
3626 def __init__(self, master=None, cnf={}, **kw):
3627 """Construct a labelframe widget with the parent MASTER.
Raymond Hettingerff41c482003-04-06 09:01:11 +00003628
Martin v. Löwis2ec36272002-10-13 10:22:08 +00003629 STANDARD OPTIONS
Raymond Hettingerff41c482003-04-06 09:01:11 +00003630
3631 borderwidth, cursor, font, foreground,
3632 highlightbackground, highlightcolor,
3633 highlightthickness, padx, pady, relief,
Martin v. Löwis2ec36272002-10-13 10:22:08 +00003634 takefocus, text
Raymond Hettingerff41c482003-04-06 09:01:11 +00003635
Martin v. Löwis2ec36272002-10-13 10:22:08 +00003636 WIDGET-SPECIFIC OPTIONS
Raymond Hettingerff41c482003-04-06 09:01:11 +00003637
3638 background, class, colormap, container,
3639 height, labelanchor, labelwidget,
Martin v. Löwis2ec36272002-10-13 10:22:08 +00003640 visual, width
3641 """
3642 Widget.__init__(self, master, 'labelframe', cnf, kw)
Raymond Hettingerff41c482003-04-06 09:01:11 +00003643
Martin v. Löwis2ec36272002-10-13 10:22:08 +00003644########################################################################
3645
3646class PanedWindow(Widget):
3647 """panedwindow widget."""
3648 def __init__(self, master=None, cnf={}, **kw):
3649 """Construct a panedwindow widget with the parent MASTER.
Raymond Hettingerff41c482003-04-06 09:01:11 +00003650
Martin v. Löwis2ec36272002-10-13 10:22:08 +00003651 STANDARD OPTIONS
Raymond Hettingerff41c482003-04-06 09:01:11 +00003652
Martin v. Löwis2ec36272002-10-13 10:22:08 +00003653 background, borderwidth, cursor, height,
3654 orient, relief, width
Raymond Hettingerff41c482003-04-06 09:01:11 +00003655
Martin v. Löwis2ec36272002-10-13 10:22:08 +00003656 WIDGET-SPECIFIC OPTIONS
Raymond Hettingerff41c482003-04-06 09:01:11 +00003657
3658 handlepad, handlesize, opaqueresize,
3659 sashcursor, sashpad, sashrelief,
Martin v. Löwis2ec36272002-10-13 10:22:08 +00003660 sashwidth, showhandle,
3661 """
3662 Widget.__init__(self, master, 'panedwindow', cnf, kw)
3663
3664 def add(self, child, **kw):
Raymond Hettingerff41c482003-04-06 09:01:11 +00003665 """Add a child widget to the panedwindow in a new pane.
3666
3667 The child argument is the name of the child widget
3668 followed by pairs of arguments that specify how to
Guilherme Polo86425562009-05-31 21:35:23 +00003669 manage the windows. The possible options and values
3670 are the ones accepted by the paneconfigure method.
Martin v. Löwis2ec36272002-10-13 10:22:08 +00003671 """
3672 self.tk.call((self._w, 'add', child) + self._options(kw))
Raymond Hettingerff41c482003-04-06 09:01:11 +00003673
Martin v. Löwis2ec36272002-10-13 10:22:08 +00003674 def remove(self, child):
3675 """Remove the pane containing child from the panedwindow
Raymond Hettingerff41c482003-04-06 09:01:11 +00003676
Martin v. Löwis2ec36272002-10-13 10:22:08 +00003677 All geometry management options for child will be forgotten.
3678 """
3679 self.tk.call(self._w, 'forget', child)
3680 forget=remove
Raymond Hettingerff41c482003-04-06 09:01:11 +00003681
Martin v. Löwis2ec36272002-10-13 10:22:08 +00003682 def identify(self, x, y):
3683 """Identify the panedwindow component at point x, y
Raymond Hettingerff41c482003-04-06 09:01:11 +00003684
3685 If the point is over a sash or a sash handle, the result
Martin v. Löwis2ec36272002-10-13 10:22:08 +00003686 is a two element list containing the index of the sash or
Raymond Hettingerff41c482003-04-06 09:01:11 +00003687 handle, and a word indicating whether it is over a sash
3688 or a handle, such as {0 sash} or {2 handle}. If the point
3689 is over any other part of the panedwindow, the result is
Martin v. Löwis2ec36272002-10-13 10:22:08 +00003690 an empty list.
3691 """
3692 return self.tk.call(self._w, 'identify', x, y)
Raymond Hettingerff41c482003-04-06 09:01:11 +00003693
Martin v. Löwis2ec36272002-10-13 10:22:08 +00003694 def proxy(self, *args):
3695 """Internal function."""
3696 return self._getints(
Raymond Hettingerff41c482003-04-06 09:01:11 +00003697 self.tk.call((self._w, 'proxy') + args)) or ()
3698
Martin v. Löwis2ec36272002-10-13 10:22:08 +00003699 def proxy_coord(self):
3700 """Return the x and y pair of the most recent proxy location
3701 """
3702 return self.proxy("coord")
Raymond Hettingerff41c482003-04-06 09:01:11 +00003703
Martin v. Löwis2ec36272002-10-13 10:22:08 +00003704 def proxy_forget(self):
3705 """Remove the proxy from the display.
3706 """
3707 return self.proxy("forget")
Raymond Hettingerff41c482003-04-06 09:01:11 +00003708
Martin v. Löwis2ec36272002-10-13 10:22:08 +00003709 def proxy_place(self, x, y):
Raymond Hettingerff41c482003-04-06 09:01:11 +00003710 """Place the proxy at the given x and y coordinates.
Martin v. Löwis2ec36272002-10-13 10:22:08 +00003711 """
3712 return self.proxy("place", x, y)
Raymond Hettingerff41c482003-04-06 09:01:11 +00003713
Martin v. Löwis2ec36272002-10-13 10:22:08 +00003714 def sash(self, *args):
3715 """Internal function."""
3716 return self._getints(
3717 self.tk.call((self._w, 'sash') + args)) or ()
Raymond Hettingerff41c482003-04-06 09:01:11 +00003718
Martin v. Löwis2ec36272002-10-13 10:22:08 +00003719 def sash_coord(self, index):
Raymond Hettingerff41c482003-04-06 09:01:11 +00003720 """Return the current x and y pair for the sash given by index.
3721
3722 Index must be an integer between 0 and 1 less than the
3723 number of panes in the panedwindow. The coordinates given are
3724 those of the top left corner of the region containing the sash.
3725 pathName sash dragto index x y This command computes the
3726 difference between the given coordinates and the coordinates
3727 given to the last sash coord command for the given sash. It then
3728 moves that sash the computed difference. The return value is the
Martin v. Löwis2ec36272002-10-13 10:22:08 +00003729 empty string.
3730 """
3731 return self.sash("coord", index)
Raymond Hettingerff41c482003-04-06 09:01:11 +00003732
Martin v. Löwis2ec36272002-10-13 10:22:08 +00003733 def sash_mark(self, index):
Raymond Hettingerff41c482003-04-06 09:01:11 +00003734 """Records x and y for the sash given by index;
3735
Martin v. Löwis2ec36272002-10-13 10:22:08 +00003736 Used in conjunction with later dragto commands to move the sash.
3737 """
3738 return self.sash("mark", index)
Raymond Hettingerff41c482003-04-06 09:01:11 +00003739
Martin v. Löwis2ec36272002-10-13 10:22:08 +00003740 def sash_place(self, index, x, y):
3741 """Place the sash given by index at the given coordinates
3742 """
3743 return self.sash("place", index, x, y)
Raymond Hettingerff41c482003-04-06 09:01:11 +00003744
Martin v. Löwis2ec36272002-10-13 10:22:08 +00003745 def panecget(self, child, option):
Raymond Hettingerff41c482003-04-06 09:01:11 +00003746 """Query a management option for window.
3747
Martin v. Löwis2ec36272002-10-13 10:22:08 +00003748 Option may be any value allowed by the paneconfigure subcommand
3749 """
3750 return self.tk.call(
3751 (self._w, 'panecget') + (child, '-'+option))
Raymond Hettingerff41c482003-04-06 09:01:11 +00003752
Martin v. Löwis2ec36272002-10-13 10:22:08 +00003753 def paneconfigure(self, tagOrId, cnf=None, **kw):
Raymond Hettingerff41c482003-04-06 09:01:11 +00003754 """Query or modify the management options for window.
3755
Martin v. Löwis2ec36272002-10-13 10:22:08 +00003756 If no option is specified, returns a list describing all
Raymond Hettingerff41c482003-04-06 09:01:11 +00003757 of the available options for pathName. If option is
3758 specified with no value, then the command returns a list
3759 describing the one named option (this list will be identical
3760 to the corresponding sublist of the value returned if no
3761 option is specified). If one or more option-value pairs are
3762 specified, then the command modifies the given widget
3763 option(s) to have the given value(s); in this case the
3764 command returns an empty string. The following options
Martin v. Löwis2ec36272002-10-13 10:22:08 +00003765 are supported:
Raymond Hettingerff41c482003-04-06 09:01:11 +00003766
Martin v. Löwis2ec36272002-10-13 10:22:08 +00003767 after window
Raymond Hettingerff41c482003-04-06 09:01:11 +00003768 Insert the window after the window specified. window
Martin v. Löwis2ec36272002-10-13 10:22:08 +00003769 should be the name of a window already managed by pathName.
3770 before window
Raymond Hettingerff41c482003-04-06 09:01:11 +00003771 Insert the window before the window specified. window
Martin v. Löwis2ec36272002-10-13 10:22:08 +00003772 should be the name of a window already managed by pathName.
3773 height size
Raymond Hettingerff41c482003-04-06 09:01:11 +00003774 Specify a height for the window. The height will be the
3775 outer dimension of the window including its border, if
3776 any. If size is an empty string, or if -height is not
3777 specified, then the height requested internally by the
3778 window will be used initially; the height may later be
3779 adjusted by the movement of sashes in the panedwindow.
Martin v. Löwis2ec36272002-10-13 10:22:08 +00003780 Size may be any value accepted by Tk_GetPixels.
3781 minsize n
Raymond Hettingerff41c482003-04-06 09:01:11 +00003782 Specifies that the size of the window cannot be made
3783 less than n. This constraint only affects the size of
3784 the widget in the paned dimension -- the x dimension
3785 for horizontal panedwindows, the y dimension for
3786 vertical panedwindows. May be any value accepted by
Martin v. Löwis2ec36272002-10-13 10:22:08 +00003787 Tk_GetPixels.
3788 padx n
Raymond Hettingerff41c482003-04-06 09:01:11 +00003789 Specifies a non-negative value indicating how much
3790 extra space to leave on each side of the window in
3791 the X-direction. The value may have any of the forms
Martin v. Löwis2ec36272002-10-13 10:22:08 +00003792 accepted by Tk_GetPixels.
3793 pady n
3794 Specifies a non-negative value indicating how much
Raymond Hettingerff41c482003-04-06 09:01:11 +00003795 extra space to leave on each side of the window in
3796 the Y-direction. The value may have any of the forms
Martin v. Löwis2ec36272002-10-13 10:22:08 +00003797 accepted by Tk_GetPixels.
3798 sticky style
Raymond Hettingerff41c482003-04-06 09:01:11 +00003799 If a window's pane is larger than the requested
3800 dimensions of the window, this option may be used
3801 to position (or stretch) the window within its pane.
3802 Style is a string that contains zero or more of the
3803 characters n, s, e or w. The string can optionally
3804 contains spaces or commas, but they are ignored. Each
3805 letter refers to a side (north, south, east, or west)
3806 that the window will "stick" to. If both n and s
3807 (or e and w) are specified, the window will be
3808 stretched to fill the entire height (or width) of
Martin v. Löwis2ec36272002-10-13 10:22:08 +00003809 its cavity.
3810 width size
Raymond Hettingerff41c482003-04-06 09:01:11 +00003811 Specify a width for the window. The width will be
3812 the outer dimension of the window including its
3813 border, if any. If size is an empty string, or
Martin v. Löwis2ec36272002-10-13 10:22:08 +00003814 if -width is not specified, then the width requested
Raymond Hettingerff41c482003-04-06 09:01:11 +00003815 internally by the window will be used initially; the
3816 width may later be adjusted by the movement of sashes
3817 in the panedwindow. Size may be any value accepted by
Martin v. Löwis2ec36272002-10-13 10:22:08 +00003818 Tk_GetPixels.
Raymond Hettingerff41c482003-04-06 09:01:11 +00003819
Martin v. Löwis2ec36272002-10-13 10:22:08 +00003820 """
3821 if cnf is None and not kw:
Serhiy Storchaka848972c2013-12-25 16:35:38 +02003822 return self._getconfigure(self._w, 'paneconfigure', tagOrId)
Guido van Rossum13257902007-06-07 23:15:56 +00003823 if isinstance(cnf, str) and not kw:
Serhiy Storchaka848972c2013-12-25 16:35:38 +02003824 return self._getconfigure1(
3825 self._w, 'paneconfigure', tagOrId, '-'+cnf)
Martin v. Löwis2ec36272002-10-13 10:22:08 +00003826 self.tk.call((self._w, 'paneconfigure', tagOrId) +
3827 self._options(cnf, kw))
3828 paneconfig = paneconfigure
3829
3830 def panes(self):
3831 """Returns an ordered list of the child panes."""
Serhiy Storchakaa21acb52014-01-07 19:27:42 +02003832 return self.tk.splitlist(self.tk.call(self._w, 'panes'))
Martin v. Löwis2ec36272002-10-13 10:22:08 +00003833
Guido van Rossumc417ef81996-08-21 23:38:59 +00003834# Test:
3835
3836def _test():
Fredrik Lundh06d28152000-08-09 18:03:12 +00003837 root = Tk()
3838 text = "This is Tcl/Tk version %s" % TclVersion
Serhiy Storchaka6716d602014-07-30 19:19:21 +03003839 text += "\nThis should be a cedilla: \xe7"
Fredrik Lundh06d28152000-08-09 18:03:12 +00003840 label = Label(root, text=text)
3841 label.pack()
3842 test = Button(root, text="Click me!",
3843 command=lambda root=root: root.test.configure(
3844 text="[%s]" % root.test['text']))
3845 test.pack()
3846 root.test = test
3847 quit = Button(root, text="QUIT", command=root.destroy)
3848 quit.pack()
3849 # The following three commands are needed so the window pops
3850 # up on top on Windows...
3851 root.iconify()
3852 root.update()
3853 root.deiconify()
3854 root.mainloop()
Guido van Rossumc417ef81996-08-21 23:38:59 +00003855
3856if __name__ == '__main__':
Fredrik Lundh06d28152000-08-09 18:03:12 +00003857 _test()