ยปCore Development>Code coverage>Lib/lib-tk/Tkinter.py

Python code coverage for Lib/lib-tk/Tkinter.py

#countcontent
1n/a"""Wrapper functions for Tcl/Tk.
2n/a
3n/aTkinter provides classes which allow the display, positioning and
4n/acontrol of widgets. Toplevel widgets are Tk and Toplevel. Other
5n/awidgets are Frame, Label, Entry, Text, Canvas, Button, Radiobutton,
6n/aCheckbutton, Scale, Listbox, Scrollbar, OptionMenu, Spinbox
7n/aLabelFrame and PanedWindow.
8n/a
9n/aProperties of the widgets are specified with keyword arguments.
10n/aKeyword arguments have the same name as the corresponding resource
11n/aunder Tk.
12n/a
13n/aWidgets are positioned with one of the geometry managers Place, Pack
14n/aor Grid. These managers can be called with methods place, pack, grid
15n/aavailable in every Widget.
16n/a
17n/aActions are bound to events by resources (e.g. keyword argument
18n/acommand) or with the method bind.
19n/a
20n/aExample (Hello, World):
21n/aimport Tkinter
22n/afrom Tkconstants import *
23n/atk = Tkinter.Tk()
24n/aframe = Tkinter.Frame(tk, relief=RIDGE, borderwidth=2)
25n/aframe.pack(fill=BOTH,expand=1)
26n/alabel = Tkinter.Label(frame, text="Hello, World")
27n/alabel.pack(fill=X, expand=1)
28n/abutton = Tkinter.Button(frame,text="Exit",command=tk.destroy)
29n/abutton.pack(side=BOTTOM)
30n/atk.mainloop()
311"""
32n/a
331__version__ = "$Revision: 81008 $"
34n/a
351import sys
361if sys.platform == "win32":
37n/a # Attempt to configure Tcl/Tk without requiring PATH
380 import FixTk
391import _tkinter # If this fails your Python may not be configured for Tk
400tkinter = _tkinter # b/w compat for export
410TclError = _tkinter.TclError
420from types import *
430from Tkconstants import *
44n/a
450wantobjects = 1
46n/a
470TkVersion = float(_tkinter.TK_VERSION)
480TclVersion = float(_tkinter.TCL_VERSION)
49n/a
500READABLE = _tkinter.READABLE
510WRITABLE = _tkinter.WRITABLE
520EXCEPTION = _tkinter.EXCEPTION
53n/a
54n/a# These are not always defined, e.g. not on Win32 with Tk 8.0 :-(
550try: _tkinter.createfilehandler
560except AttributeError: _tkinter.createfilehandler = None
570try: _tkinter.deletefilehandler
580except AttributeError: _tkinter.deletefilehandler = None
59n/a
60n/a
610def _flatten(tuple):
62n/a """Internal function."""
630 res = ()
640 for item in tuple:
650 if type(item) in (TupleType, ListType):
660 res = res + _flatten(item)
670 elif item is not None:
680 res = res + (item,)
690 return res
70n/a
710try: _flatten = _tkinter._flatten
720except AttributeError: pass
73n/a
740def _cnfmerge(cnfs):
75n/a """Internal function."""
760 if type(cnfs) is DictionaryType:
770 return cnfs
780 elif type(cnfs) in (NoneType, StringType):
790 return cnfs
80n/a else:
810 cnf = {}
820 for c in _flatten(cnfs):
830 try:
840 cnf.update(c)
850 except (AttributeError, TypeError), msg:
860 print "_cnfmerge: fallback due to:", msg
870 for k, v in c.items():
880 cnf[k] = v
890 return cnf
90n/a
910try: _cnfmerge = _tkinter._cnfmerge
920except AttributeError: pass
93n/a
940class Event:
95n/a """Container for the properties of an event.
96n/a
97n/a Instances of this type are generated if one of the following events occurs:
98n/a
99n/a KeyPress, KeyRelease - for keyboard events
100n/a ButtonPress, ButtonRelease, Motion, Enter, Leave, MouseWheel - for mouse events
101n/a Visibility, Unmap, Map, Expose, FocusIn, FocusOut, Circulate,
102n/a Colormap, Gravity, Reparent, Property, Destroy, Activate,
103n/a Deactivate - for window events.
104n/a
105n/a If a callback function for one of these events is registered
106n/a using bind, bind_all, bind_class, or tag_bind, the callback is
107n/a called with an Event as first argument. It will have the
108n/a following attributes (in braces are the event types for which
109n/a the attribute is valid):
110n/a
111n/a serial - serial number of event
112n/a num - mouse button pressed (ButtonPress, ButtonRelease)
113n/a focus - whether the window has the focus (Enter, Leave)
114n/a height - height of the exposed window (Configure, Expose)
115n/a width - width of the exposed window (Configure, Expose)
116n/a keycode - keycode of the pressed key (KeyPress, KeyRelease)
117n/a state - state of the event as a number (ButtonPress, ButtonRelease,
118n/a Enter, KeyPress, KeyRelease,
119n/a Leave, Motion)
120n/a state - state as a string (Visibility)
121n/a time - when the event occurred
122n/a x - x-position of the mouse
123n/a y - y-position of the mouse
124n/a x_root - x-position of the mouse on the screen
125n/a (ButtonPress, ButtonRelease, KeyPress, KeyRelease, Motion)
126n/a y_root - y-position of the mouse on the screen
127n/a (ButtonPress, ButtonRelease, KeyPress, KeyRelease, Motion)
128n/a char - pressed character (KeyPress, KeyRelease)
129n/a send_event - see X/Windows documentation
130n/a keysym - keysym of the event as a string (KeyPress, KeyRelease)
131n/a keysym_num - keysym of the event as a number (KeyPress, KeyRelease)
132n/a type - type of the event as a number
133n/a widget - widget in which the event occurred
134n/a delta - delta of wheel movement (MouseWheel)
135n/a """
1360 pass
137n/a
1380_support_default_root = 1
1390_default_root = None
140n/a
1410def NoDefaultRoot():
142n/a """Inhibit setting of default root window.
143n/a
144n/a Call this function to inhibit that the first instance of
145n/a Tk is used for windows without an explicit parent window.
146n/a """
147n/a global _support_default_root
1480 _support_default_root = 0
149n/a global _default_root
1500 _default_root = None
1510 del _default_root
152n/a
1530def _tkerror(err):
154n/a """Internal function."""
1550 pass
156n/a
1570def _exit(code='0'):
158n/a """Internal function. Calling it will throw the exception SystemExit."""
1590 raise SystemExit, code
160n/a
1610_varnum = 0
1620class Variable:
163n/a """Class to define value holders for e.g. buttons.
164n/a
165n/a Subclasses StringVar, IntVar, DoubleVar, BooleanVar are specializations
166n/a that constrain the type of the value returned from get()."""
1670 _default = ""
1680 def __init__(self, master=None, value=None, name=None):
169n/a """Construct a variable
170n/a
171n/a MASTER can be given as master widget.
172n/a VALUE is an optional value (defaults to "")
173n/a NAME is an optional Tcl name (defaults to PY_VARnum).
174n/a
175n/a If NAME matches an existing variable and VALUE is omitted
176n/a then the existing value is retained.
177n/a """
178n/a global _varnum
1790 if not master:
1800 master = _default_root
1810 self._master = master
1820 self._tk = master.tk
1830 if name:
1840 self._name = name
185n/a else:
1860 self._name = 'PY_VAR' + repr(_varnum)
1870 _varnum += 1
1880 if value is not None:
1890 self.set(value)
1900 elif not self._tk.call("info", "exists", self._name):
1910 self.set(self._default)
1920 def __del__(self):
193n/a """Unset the variable in Tcl."""
1940 self._tk.globalunsetvar(self._name)
1950 def __str__(self):
196n/a """Return the name of the variable in Tcl."""
1970 return self._name
1980 def set(self, value):
199n/a """Set the variable to VALUE."""
2000 return self._tk.globalsetvar(self._name, value)
2010 def get(self):
202n/a """Return value of variable."""
2030 return self._tk.globalgetvar(self._name)
2040 def trace_variable(self, mode, callback):
205n/a """Define a trace callback for the variable.
206n/a
207n/a MODE is one of "r", "w", "u" for read, write, undefine.
208n/a CALLBACK must be a function which is called when
209n/a the variable is read, written or undefined.
210n/a
211n/a Return the name of the callback.
212n/a """
2130 cbname = self._master._register(callback)
2140 self._tk.call("trace", "variable", self._name, mode, cbname)
2150 return cbname
2160 trace = trace_variable
2170 def trace_vdelete(self, mode, cbname):
218n/a """Delete the trace callback for a variable.
219n/a
220n/a MODE is one of "r", "w", "u" for read, write, undefine.
221n/a CBNAME is the name of the callback returned from trace_variable or trace.
222n/a """
2230 self._tk.call("trace", "vdelete", self._name, mode, cbname)
2240 self._master.deletecommand(cbname)
2250 def trace_vinfo(self):
226n/a """Return all trace callback information."""
2270 return map(self._tk.split, self._tk.splitlist(
2280 self._tk.call("trace", "vinfo", self._name)))
2290 def __eq__(self, other):
230n/a """Comparison for equality (==).
231n/a
232n/a Note: if the Variable's master matters to behavior
233n/a also compare self._master == other._master
234n/a """
2350 return self.__class__.__name__ == other.__class__.__name__ \
2360 and self._name == other._name
237n/a
2380class StringVar(Variable):
239n/a """Value holder for strings variables."""
2400 _default = ""
2410 def __init__(self, master=None, value=None, name=None):
242n/a """Construct a string variable.
243n/a
244n/a MASTER can be given as master widget.
245n/a VALUE is an optional value (defaults to "")
246n/a NAME is an optional Tcl name (defaults to PY_VARnum).
247n/a
248n/a If NAME matches an existing variable and VALUE is omitted
249n/a then the existing value is retained.
250n/a """
2510 Variable.__init__(self, master, value, name)
252n/a
2530 def get(self):
254n/a """Return value of variable as string."""
2550 value = self._tk.globalgetvar(self._name)
2560 if isinstance(value, basestring):
2570 return value
2580 return str(value)
259n/a
2600class IntVar(Variable):
261n/a """Value holder for integer variables."""
2620 _default = 0
2630 def __init__(self, master=None, value=None, name=None):
264n/a """Construct an integer variable.
265n/a
266n/a MASTER can be given as master widget.
267n/a VALUE is an optional value (defaults to 0)
268n/a NAME is an optional Tcl name (defaults to PY_VARnum).
269n/a
270n/a If NAME matches an existing variable and VALUE is omitted
271n/a then the existing value is retained.
272n/a """
2730 Variable.__init__(self, master, value, name)
274n/a
2750 def set(self, value):
276n/a """Set the variable to value, converting booleans to integers."""
2770 if isinstance(value, bool):
2780 value = int(value)
2790 return Variable.set(self, value)
280n/a
2810 def get(self):
282n/a """Return the value of the variable as an integer."""
2830 return getint(self._tk.globalgetvar(self._name))
284n/a
2850class DoubleVar(Variable):
286n/a """Value holder for float variables."""
2870 _default = 0.0
2880 def __init__(self, master=None, value=None, name=None):
289n/a """Construct a float variable.
290n/a
291n/a MASTER can be given as master widget.
292n/a VALUE is an optional value (defaults to 0.0)
293n/a NAME is an optional Tcl name (defaults to PY_VARnum).
294n/a
295n/a If NAME matches an existing variable and VALUE is omitted
296n/a then the existing value is retained.
297n/a """
2980 Variable.__init__(self, master, value, name)
299n/a
3000 def get(self):
301n/a """Return the value of the variable as a float."""
3020 return getdouble(self._tk.globalgetvar(self._name))
303n/a
3040class BooleanVar(Variable):
305n/a """Value holder for boolean variables."""
3060 _default = False
3070 def __init__(self, master=None, value=None, name=None):
308n/a """Construct a boolean variable.
309n/a
310n/a MASTER can be given as master widget.
311n/a VALUE is an optional value (defaults to False)
312n/a NAME is an optional Tcl name (defaults to PY_VARnum).
313n/a
314n/a If NAME matches an existing variable and VALUE is omitted
315n/a then the existing value is retained.
316n/a """
3170 Variable.__init__(self, master, value, name)
318n/a
3190 def get(self):
320n/a """Return the value of the variable as a bool."""
3210 return self._tk.getboolean(self._tk.globalgetvar(self._name))
322n/a
3230def mainloop(n=0):
324n/a """Run the main loop of Tcl."""
3250 _default_root.tk.mainloop(n)
326n/a
3270getint = int
328n/a
3290getdouble = float
330n/a
3310def getboolean(s):
332n/a """Convert true and false to integer values 1 and 0."""
3330 return _default_root.tk.getboolean(s)
334n/a
335n/a# Methods defined on both toplevel and interior widgets
3360class Misc:
337n/a """Internal class.
338n/a
339n/a Base class which defines methods common for interior widgets."""
340n/a
341n/a # XXX font command?
3420 _tclCommands = None
3430 def destroy(self):
344n/a """Internal function.
345n/a
346n/a Delete all Tcl commands created for
347n/a this widget in the Tcl interpreter."""
3480 if self._tclCommands is not None:
3490 for name in self._tclCommands:
350n/a #print '- Tkinter: deleted command', name
3510 self.tk.deletecommand(name)
3520 self._tclCommands = None
3530 def deletecommand(self, name):
354n/a """Internal function.
355n/a
356n/a Delete the Tcl command provided in NAME."""
357n/a #print '- Tkinter: deleted command', name
3580 self.tk.deletecommand(name)
3590 try:
3600 self._tclCommands.remove(name)
3610 except ValueError:
3620 pass
3630 def tk_strictMotif(self, boolean=None):
364n/a """Set Tcl internal variable, whether the look and feel
365n/a should adhere to Motif.
366n/a
367n/a A parameter of 1 means adhere to Motif (e.g. no color
368n/a change if mouse passes over slider).
369n/a Returns the set value."""
3700 return self.tk.getboolean(self.tk.call(
3710 'set', 'tk_strictMotif', boolean))
3720 def tk_bisque(self):
373n/a """Change the color scheme to light brown as used in Tk 3.6 and before."""
3740 self.tk.call('tk_bisque')
3750 def tk_setPalette(self, *args, **kw):
376n/a """Set a new color scheme for all widget elements.
377n/a
378n/a A single color as argument will cause that all colors of Tk
379n/a widget elements are derived from this.
380n/a Alternatively several keyword parameters and its associated
381n/a colors can be given. The following keywords are valid:
382n/a activeBackground, foreground, selectColor,
383n/a activeForeground, highlightBackground, selectBackground,
384n/a background, highlightColor, selectForeground,
385n/a disabledForeground, insertBackground, troughColor."""
3860 self.tk.call(('tk_setPalette',)
3870 + _flatten(args) + _flatten(kw.items()))
3880 def tk_menuBar(self, *args):
389n/a """Do not use. Needed in Tk 3.6 and earlier."""
3900 pass # obsolete since Tk 4.0
3910 def wait_variable(self, name='PY_VAR'):
392n/a """Wait until the variable is modified.
393n/a
394n/a A parameter of type IntVar, StringVar, DoubleVar or
395n/a BooleanVar must be given."""
3960 self.tk.call('tkwait', 'variable', name)
3970 waitvar = wait_variable # XXX b/w compat
3980 def wait_window(self, window=None):
399n/a """Wait until a WIDGET is destroyed.
400n/a
401n/a If no parameter is given self is used."""
4020 if window is None:
4030 window = self
4040 self.tk.call('tkwait', 'window', window._w)
4050 def wait_visibility(self, window=None):
406n/a """Wait until the visibility of a WIDGET changes
407n/a (e.g. it appears).
408n/a
409n/a If no parameter is given self is used."""
4100 if window is None:
4110 window = self
4120 self.tk.call('tkwait', 'visibility', window._w)
4130 def setvar(self, name='PY_VAR', value='1'):
414n/a """Set Tcl variable NAME to VALUE."""
4150 self.tk.setvar(name, value)
4160 def getvar(self, name='PY_VAR'):
417n/a """Return value of Tcl variable NAME."""
4180 return self.tk.getvar(name)
4190 getint = int
4200 getdouble = float
4210 def getboolean(self, s):
422n/a """Return a boolean value for Tcl boolean values true and false given as parameter."""
4230 return self.tk.getboolean(s)
4240 def focus_set(self):
425n/a """Direct input focus to this widget.
426n/a
427n/a If the application currently does not have the focus
428n/a this widget will get the focus if the application gets
429n/a the focus through the window manager."""
4300 self.tk.call('focus', self._w)
4310 focus = focus_set # XXX b/w compat?
4320 def focus_force(self):
433n/a """Direct input focus to this widget even if the
434n/a application does not have the focus. Use with
435n/a caution!"""
4360 self.tk.call('focus', '-force', self._w)
4370 def focus_get(self):
438n/a """Return the widget which has currently the focus in the
439n/a application.
440n/a
441n/a Use focus_displayof to allow working with several
442n/a displays. Return None if application does not have
443n/a the focus."""
4440 name = self.tk.call('focus')
4450 if name == 'none' or not name: return None
4460 return self._nametowidget(name)
4470 def focus_displayof(self):
448n/a """Return the widget which has currently the focus on the
449n/a display where this widget is located.
450n/a
451n/a Return None if the application does not have the focus."""
4520 name = self.tk.call('focus', '-displayof', self._w)
4530 if name == 'none' or not name: return None
4540 return self._nametowidget(name)
4550 def focus_lastfor(self):
456n/a """Return the widget which would have the focus if top level
457n/a for this widget gets the focus from the window manager."""
4580 name = self.tk.call('focus', '-lastfor', self._w)
4590 if name == 'none' or not name: return None
4600 return self._nametowidget(name)
4610 def tk_focusFollowsMouse(self):
462n/a """The widget under mouse will get automatically focus. Can not
463n/a be disabled easily."""
4640 self.tk.call('tk_focusFollowsMouse')
4650 def tk_focusNext(self):
466n/a """Return the next widget in the focus order which follows
467n/a widget which has currently the focus.
468n/a
469n/a The focus order first goes to the next child, then to
470n/a the children of the child recursively and then to the
471n/a next sibling which is higher in the stacking order. A
472n/a widget is omitted if it has the takefocus resource set
473n/a to 0."""
4740 name = self.tk.call('tk_focusNext', self._w)
4750 if not name: return None
4760 return self._nametowidget(name)
4770 def tk_focusPrev(self):
478n/a """Return previous widget in the focus order. See tk_focusNext for details."""
4790 name = self.tk.call('tk_focusPrev', self._w)
4800 if not name: return None
4810 return self._nametowidget(name)
4820 def after(self, ms, func=None, *args):
483n/a """Call function once after given time.
484n/a
485n/a MS specifies the time in milliseconds. FUNC gives the
486n/a function which shall be called. Additional parameters
487n/a are given as parameters to the function call. Return
488n/a identifier to cancel scheduling with after_cancel."""
4890 if not func:
490n/a # I'd rather use time.sleep(ms*0.001)
4910 self.tk.call('after', ms)
492n/a else:
4930 def callit():
4940 try:
4950 func(*args)
496n/a finally:
4970 try:
4980 self.deletecommand(name)
4990 except TclError:
5000 pass
5010 name = self._register(callit)
5020 return self.tk.call('after', ms, name)
5030 def after_idle(self, func, *args):
504n/a """Call FUNC once if the Tcl main loop has no event to
505n/a process.
506n/a
507n/a Return an identifier to cancel the scheduling with
508n/a after_cancel."""
5090 return self.after('idle', func, *args)
5100 def after_cancel(self, id):
511n/a """Cancel scheduling of function identified with ID.
512n/a
513n/a Identifier returned by after or after_idle must be
514n/a given as first parameter."""
5150 try:
5160 data = self.tk.call('after', 'info', id)
517n/a # In Tk 8.3, splitlist returns: (script, type)
518n/a # In Tk 8.4, splitlist may return (script, type) or (script,)
5190 script = self.tk.splitlist(data)[0]
5200 self.deletecommand(script)
5210 except TclError:
5220 pass
5230 self.tk.call('after', 'cancel', id)
5240 def bell(self, displayof=0):
525n/a """Ring a display's bell."""
5260 self.tk.call(('bell',) + self._displayof(displayof))
527n/a
528n/a # Clipboard handling:
5290 def clipboard_get(self, **kw):
530n/a """Retrieve data from the clipboard on window's display.
531n/a
532n/a The window keyword defaults to the root window of the Tkinter
533n/a application.
534n/a
535n/a The type keyword specifies the form in which the data is
536n/a to be returned and should be an atom name such as STRING
537n/a or FILE_NAME. Type defaults to STRING.
538n/a
539n/a This command is equivalent to:
540n/a
541n/a selection_get(CLIPBOARD)
542n/a """
5430 return self.tk.call(('clipboard', 'get') + self._options(kw))
544n/a
5450 def clipboard_clear(self, **kw):
546n/a """Clear the data in the Tk clipboard.
547n/a
548n/a A widget specified for the optional displayof keyword
549n/a argument specifies the target display."""
5500 if 'displayof' not in kw: kw['displayof'] = self._w
5510 self.tk.call(('clipboard', 'clear') + self._options(kw))
5520 def clipboard_append(self, string, **kw):
553n/a """Append STRING to the Tk clipboard.
554n/a
555n/a A widget specified at the optional displayof keyword
556n/a argument specifies the target display. The clipboard
557n/a can be retrieved with selection_get."""
5580 if 'displayof' not in kw: kw['displayof'] = self._w
5590 self.tk.call(('clipboard', 'append') + self._options(kw)
5600 + ('--', string))
561n/a # XXX grab current w/o window argument
5620 def grab_current(self):
563n/a """Return widget which has currently the grab in this application
564n/a or None."""
5650 name = self.tk.call('grab', 'current', self._w)
5660 if not name: return None
5670 return self._nametowidget(name)
5680 def grab_release(self):
569n/a """Release grab for this widget if currently set."""
5700 self.tk.call('grab', 'release', self._w)
5710 def grab_set(self):
572n/a """Set grab for this widget.
573n/a
574n/a A grab directs all events to this and descendant
575n/a widgets in the application."""
5760 self.tk.call('grab', 'set', self._w)
5770 def grab_set_global(self):
578n/a """Set global grab for this widget.
579n/a
580n/a A global grab directs all events to this and
581n/a descendant widgets on the display. Use with caution -
582n/a other applications do not get events anymore."""
5830 self.tk.call('grab', 'set', '-global', self._w)
5840 def grab_status(self):
585n/a """Return None, "local" or "global" if this widget has
586n/a no, a local or a global grab."""
5870 status = self.tk.call('grab', 'status', self._w)
5880 if status == 'none': status = None
5890 return status
5900 def option_add(self, pattern, value, priority = None):
591n/a """Set a VALUE (second parameter) for an option
592n/a PATTERN (first parameter).
593n/a
594n/a An optional third parameter gives the numeric priority
595n/a (defaults to 80)."""
5960 self.tk.call('option', 'add', pattern, value, priority)
5970 def option_clear(self):
598n/a """Clear the option database.
599n/a
600n/a It will be reloaded if option_add is called."""
6010 self.tk.call('option', 'clear')
6020 def option_get(self, name, className):
603n/a """Return the value for an option NAME for this widget
604n/a with CLASSNAME.
605n/a
606n/a Values with higher priority override lower values."""
6070 return self.tk.call('option', 'get', self._w, name, className)
6080 def option_readfile(self, fileName, priority = None):
609n/a """Read file FILENAME into the option database.
610n/a
611n/a An optional second parameter gives the numeric
612n/a priority."""
6130 self.tk.call('option', 'readfile', fileName, priority)
6140 def selection_clear(self, **kw):
615n/a """Clear the current X selection."""
6160 if 'displayof' not in kw: kw['displayof'] = self._w
6170 self.tk.call(('selection', 'clear') + self._options(kw))
6180 def selection_get(self, **kw):
619n/a """Return the contents of the current X selection.
620n/a
621n/a A keyword parameter selection specifies the name of
622n/a the selection and defaults to PRIMARY. A keyword
623n/a parameter displayof specifies a widget on the display
624n/a to use."""
6250 if 'displayof' not in kw: kw['displayof'] = self._w
6260 return self.tk.call(('selection', 'get') + self._options(kw))
6270 def selection_handle(self, command, **kw):
628n/a """Specify a function COMMAND to call if the X
629n/a selection owned by this widget is queried by another
630n/a application.
631n/a
632n/a This function must return the contents of the
633n/a selection. The function will be called with the
634n/a arguments OFFSET and LENGTH which allows the chunking
635n/a of very long selections. The following keyword
636n/a parameters can be provided:
637n/a selection - name of the selection (default PRIMARY),
638n/a type - type of the selection (e.g. STRING, FILE_NAME)."""
6390 name = self._register(command)
6400 self.tk.call(('selection', 'handle') + self._options(kw)
6410 + (self._w, name))
6420 def selection_own(self, **kw):
643n/a """Become owner of X selection.
644n/a
645n/a A keyword parameter selection specifies the name of
646n/a the selection (default PRIMARY)."""
6470 self.tk.call(('selection', 'own') +
6480 self._options(kw) + (self._w,))
6490 def selection_own_get(self, **kw):
650n/a """Return owner of X selection.
651n/a
652n/a The following keyword parameter can
653n/a be provided:
654n/a selection - name of the selection (default PRIMARY),
655n/a type - type of the selection (e.g. STRING, FILE_NAME)."""
6560 if 'displayof' not in kw: kw['displayof'] = self._w
6570 name = self.tk.call(('selection', 'own') + self._options(kw))
6580 if not name: return None
6590 return self._nametowidget(name)
6600 def send(self, interp, cmd, *args):
661n/a """Send Tcl command CMD to different interpreter INTERP to be executed."""
6620 return self.tk.call(('send', interp, cmd) + args)
6630 def lower(self, belowThis=None):
664n/a """Lower this widget in the stacking order."""
6650 self.tk.call('lower', self._w, belowThis)
6660 def tkraise(self, aboveThis=None):
667n/a """Raise this widget in the stacking order."""
6680 self.tk.call('raise', self._w, aboveThis)
6690 lift = tkraise
6700 def colormodel(self, value=None):
671n/a """Useless. Not implemented in Tk."""
6720 return self.tk.call('tk', 'colormodel', self._w, value)
6730 def winfo_atom(self, name, displayof=0):
674n/a """Return integer which represents atom NAME."""
6750 args = ('winfo', 'atom') + self._displayof(displayof) + (name,)
6760 return getint(self.tk.call(args))
6770 def winfo_atomname(self, id, displayof=0):
678n/a """Return name of atom with identifier ID."""
679n/a args = ('winfo', 'atomname') \
6800 + self._displayof(displayof) + (id,)
6810 return self.tk.call(args)
6820 def winfo_cells(self):
683n/a """Return number of cells in the colormap for this widget."""
6840 return getint(
6850 self.tk.call('winfo', 'cells', self._w))
6860 def winfo_children(self):
687n/a """Return a list of all widgets which are children of this widget."""
6880 result = []
6890 for child in self.tk.splitlist(
6900 self.tk.call('winfo', 'children', self._w)):
6910 try:
692n/a # Tcl sometimes returns extra windows, e.g. for
693n/a # menus; those need to be skipped
6940 result.append(self._nametowidget(child))
6950 except KeyError:
6960 pass
6970 return result
698n/a
6990 def winfo_class(self):
700n/a """Return window class name of this widget."""
7010 return self.tk.call('winfo', 'class', self._w)
7020 def winfo_colormapfull(self):
703n/a """Return true if at the last color request the colormap was full."""
7040 return self.tk.getboolean(
7050 self.tk.call('winfo', 'colormapfull', self._w))
7060 def winfo_containing(self, rootX, rootY, displayof=0):
707n/a """Return the widget which is at the root coordinates ROOTX, ROOTY."""
708n/a args = ('winfo', 'containing') \
7090 + self._displayof(displayof) + (rootX, rootY)
7100 name = self.tk.call(args)
7110 if not name: return None
7120 return self._nametowidget(name)
7130 def winfo_depth(self):
714n/a """Return the number of bits per pixel."""
7150 return getint(self.tk.call('winfo', 'depth', self._w))
7160 def winfo_exists(self):
717n/a """Return true if this widget exists."""
7180 return getint(
7190 self.tk.call('winfo', 'exists', self._w))
7200 def winfo_fpixels(self, number):
721n/a """Return the number of pixels for the given distance NUMBER
722n/a (e.g. "3c") as float."""
7230 return getdouble(self.tk.call(
7240 'winfo', 'fpixels', self._w, number))
7250 def winfo_geometry(self):
726n/a """Return geometry string for this widget in the form "widthxheight+X+Y"."""
7270 return self.tk.call('winfo', 'geometry', self._w)
7280 def winfo_height(self):
729n/a """Return height of this widget."""
7300 return getint(
7310 self.tk.call('winfo', 'height', self._w))
7320 def winfo_id(self):
733n/a """Return identifier ID for this widget."""
7340 return self.tk.getint(
7350 self.tk.call('winfo', 'id', self._w))
7360 def winfo_interps(self, displayof=0):
737n/a """Return the name of all Tcl interpreters for this display."""
7380 args = ('winfo', 'interps') + self._displayof(displayof)
7390 return self.tk.splitlist(self.tk.call(args))
7400 def winfo_ismapped(self):
741n/a """Return true if this widget is mapped."""
7420 return getint(
7430 self.tk.call('winfo', 'ismapped', self._w))
7440 def winfo_manager(self):
745n/a """Return the window mananger name for this widget."""
7460 return self.tk.call('winfo', 'manager', self._w)
7470 def winfo_name(self):
748n/a """Return the name of this widget."""
7490 return self.tk.call('winfo', 'name', self._w)
7500 def winfo_parent(self):
751n/a """Return the name of the parent of this widget."""
7520 return self.tk.call('winfo', 'parent', self._w)
7530 def winfo_pathname(self, id, displayof=0):
754n/a """Return the pathname of the widget given by ID."""
755n/a args = ('winfo', 'pathname') \
7560 + self._displayof(displayof) + (id,)
7570 return self.tk.call(args)
7580 def winfo_pixels(self, number):
759n/a """Rounded integer value of winfo_fpixels."""
7600 return getint(
7610 self.tk.call('winfo', 'pixels', self._w, number))
7620 def winfo_pointerx(self):
763n/a """Return the x coordinate of the pointer on the root window."""
7640 return getint(
7650 self.tk.call('winfo', 'pointerx', self._w))
7660 def winfo_pointerxy(self):
767n/a """Return a tuple of x and y coordinates of the pointer on the root window."""
7680 return self._getints(
7690 self.tk.call('winfo', 'pointerxy', self._w))
7700 def winfo_pointery(self):
771n/a """Return the y coordinate of the pointer on the root window."""
7720 return getint(
7730 self.tk.call('winfo', 'pointery', self._w))
7740 def winfo_reqheight(self):
775n/a """Return requested height of this widget."""
7760 return getint(
7770 self.tk.call('winfo', 'reqheight', self._w))
7780 def winfo_reqwidth(self):
779n/a """Return requested width of this widget."""
7800 return getint(
7810 self.tk.call('winfo', 'reqwidth', self._w))
7820 def winfo_rgb(self, color):
783n/a """Return tuple of decimal values for red, green, blue for
784n/a COLOR in this widget."""
7850 return self._getints(
7860 self.tk.call('winfo', 'rgb', self._w, color))
7870 def winfo_rootx(self):
788n/a """Return x coordinate of upper left corner of this widget on the
789n/a root window."""
7900 return getint(
7910 self.tk.call('winfo', 'rootx', self._w))
7920 def winfo_rooty(self):
793n/a """Return y coordinate of upper left corner of this widget on the
794n/a root window."""
7950 return getint(
7960 self.tk.call('winfo', 'rooty', self._w))
7970 def winfo_screen(self):
798n/a """Return the screen name of this widget."""
7990 return self.tk.call('winfo', 'screen', self._w)
8000 def winfo_screencells(self):
801n/a """Return the number of the cells in the colormap of the screen
802n/a of this widget."""
8030 return getint(
8040 self.tk.call('winfo', 'screencells', self._w))
8050 def winfo_screendepth(self):
806n/a """Return the number of bits per pixel of the root window of the
807n/a screen of this widget."""
8080 return getint(
8090 self.tk.call('winfo', 'screendepth', self._w))
8100 def winfo_screenheight(self):
811n/a """Return the number of pixels of the height of the screen of this widget
812n/a in pixel."""
8130 return getint(
8140 self.tk.call('winfo', 'screenheight', self._w))
8150 def winfo_screenmmheight(self):
816n/a """Return the number of pixels of the height of the screen of
817n/a this widget in mm."""
8180 return getint(
8190 self.tk.call('winfo', 'screenmmheight', self._w))
8200 def winfo_screenmmwidth(self):
821n/a """Return the number of pixels of the width of the screen of
822n/a this widget in mm."""
8230 return getint(
8240 self.tk.call('winfo', 'screenmmwidth', self._w))
8250 def winfo_screenvisual(self):
826n/a """Return one of the strings directcolor, grayscale, pseudocolor,
827n/a staticcolor, staticgray, or truecolor for the default
828n/a colormodel of this screen."""
8290 return self.tk.call('winfo', 'screenvisual', self._w)
8300 def winfo_screenwidth(self):
831n/a """Return the number of pixels of the width of the screen of
832n/a this widget in pixel."""
8330 return getint(
8340 self.tk.call('winfo', 'screenwidth', self._w))
8350 def winfo_server(self):
836n/a """Return information of the X-Server of the screen of this widget in
837n/a the form "XmajorRminor vendor vendorVersion"."""
8380 return self.tk.call('winfo', 'server', self._w)
8390 def winfo_toplevel(self):
840n/a """Return the toplevel widget of this widget."""
8410 return self._nametowidget(self.tk.call(
8420 'winfo', 'toplevel', self._w))
8430 def winfo_viewable(self):
844n/a """Return true if the widget and all its higher ancestors are mapped."""
8450 return getint(
8460 self.tk.call('winfo', 'viewable', self._w))
8470 def winfo_visual(self):
848n/a """Return one of the strings directcolor, grayscale, pseudocolor,
849n/a staticcolor, staticgray, or truecolor for the
850n/a colormodel of this widget."""
8510 return self.tk.call('winfo', 'visual', self._w)
8520 def winfo_visualid(self):
853n/a """Return the X identifier for the visual for this widget."""
8540 return self.tk.call('winfo', 'visualid', self._w)
8550 def winfo_visualsavailable(self, includeids=0):
856n/a """Return a list of all visuals available for the screen
857n/a of this widget.
858n/a
859n/a Each item in the list consists of a visual name (see winfo_visual), a
860n/a depth and if INCLUDEIDS=1 is given also the X identifier."""
8610 data = self.tk.split(
8620 self.tk.call('winfo', 'visualsavailable', self._w,
8630 includeids and 'includeids' or None))
8640 if type(data) is StringType:
8650 data = [self.tk.split(data)]
8660 return map(self.__winfo_parseitem, data)
8670 def __winfo_parseitem(self, t):
868n/a """Internal function."""
8690 return t[:1] + tuple(map(self.__winfo_getint, t[1:]))
8700 def __winfo_getint(self, x):
871n/a """Internal function."""
8720 return int(x, 0)
8730 def winfo_vrootheight(self):
874n/a """Return the height of the virtual root window associated with this
875n/a widget in pixels. If there is no virtual root window return the
876n/a height of the screen."""
8770 return getint(
8780 self.tk.call('winfo', 'vrootheight', self._w))
8790 def winfo_vrootwidth(self):
880n/a """Return the width of the virtual root window associated with this
881n/a widget in pixel. If there is no virtual root window return the
882n/a width of the screen."""
8830 return getint(
8840 self.tk.call('winfo', 'vrootwidth', self._w))
8850 def winfo_vrootx(self):
886n/a """Return the x offset of the virtual root relative to the root
887n/a window of the screen of this widget."""
8880 return getint(
8890 self.tk.call('winfo', 'vrootx', self._w))
8900 def winfo_vrooty(self):
891n/a """Return the y offset of the virtual root relative to the root
892n/a window of the screen of this widget."""
8930 return getint(
8940 self.tk.call('winfo', 'vrooty', self._w))
8950 def winfo_width(self):
896n/a """Return the width of this widget."""
8970 return getint(
8980 self.tk.call('winfo', 'width', self._w))
8990 def winfo_x(self):
900n/a """Return the x coordinate of the upper left corner of this widget
901n/a in the parent."""
9020 return getint(
9030 self.tk.call('winfo', 'x', self._w))
9040 def winfo_y(self):
905n/a """Return the y coordinate of the upper left corner of this widget
906n/a in the parent."""
9070 return getint(
9080 self.tk.call('winfo', 'y', self._w))
9090 def update(self):
910n/a """Enter event loop until all pending events have been processed by Tcl."""
9110 self.tk.call('update')
9120 def update_idletasks(self):
913n/a """Enter event loop until all idle callbacks have been called. This
914n/a will update the display of windows but not process events caused by
915n/a the user."""
9160 self.tk.call('update', 'idletasks')
9170 def bindtags(self, tagList=None):
918n/a """Set or get the list of bindtags for this widget.
919n/a
920n/a With no argument return the list of all bindtags associated with
921n/a this widget. With a list of strings as argument the bindtags are
922n/a set to this list. The bindtags determine in which order events are
923n/a processed (see bind)."""
9240 if tagList is None:
9250 return self.tk.splitlist(
9260 self.tk.call('bindtags', self._w))
927n/a else:
9280 self.tk.call('bindtags', self._w, tagList)
9290 def _bind(self, what, sequence, func, add, needcleanup=1):
930n/a """Internal function."""
9310 if type(func) is StringType:
9320 self.tk.call(what + (sequence, func))
9330 elif func:
9340 funcid = self._register(func, self._substitute,
9350 needcleanup)
9360 cmd = ('%sif {"[%s %s]" == "break"} break\n'
937n/a %
9380 (add and '+' or '',
9390 funcid, self._subst_format_str))
9400 self.tk.call(what + (sequence, cmd))
9410 return funcid
9420 elif sequence:
9430 return self.tk.call(what + (sequence,))
944n/a else:
9450 return self.tk.splitlist(self.tk.call(what))
9460 def bind(self, sequence=None, func=None, add=None):
947n/a """Bind to this widget at event SEQUENCE a call to function FUNC.
948n/a
949n/a SEQUENCE is a string of concatenated event
950n/a patterns. An event pattern is of the form
951n/a <MODIFIER-MODIFIER-TYPE-DETAIL> where MODIFIER is one
952n/a of Control, Mod2, M2, Shift, Mod3, M3, Lock, Mod4, M4,
953n/a Button1, B1, Mod5, M5 Button2, B2, Meta, M, Button3,
954n/a B3, Alt, Button4, B4, Double, Button5, B5 Triple,
955n/a Mod1, M1. TYPE is one of Activate, Enter, Map,
956n/a ButtonPress, Button, Expose, Motion, ButtonRelease
957n/a FocusIn, MouseWheel, Circulate, FocusOut, Property,
958n/a Colormap, Gravity Reparent, Configure, KeyPress, Key,
959n/a Unmap, Deactivate, KeyRelease Visibility, Destroy,
960n/a Leave and DETAIL is the button number for ButtonPress,
961n/a ButtonRelease and DETAIL is the Keysym for KeyPress and
962n/a KeyRelease. Examples are
963n/a <Control-Button-1> for pressing Control and mouse button 1 or
964n/a <Alt-A> for pressing A and the Alt key (KeyPress can be omitted).
965n/a An event pattern can also be a virtual event of the form
966n/a <<AString>> where AString can be arbitrary. This
967n/a event can be generated by event_generate.
968n/a If events are concatenated they must appear shortly
969n/a after each other.
970n/a
971n/a FUNC will be called if the event sequence occurs with an
972n/a instance of Event as argument. If the return value of FUNC is
973n/a "break" no further bound function is invoked.
974n/a
975n/a An additional boolean parameter ADD specifies whether FUNC will
976n/a be called additionally to the other bound function or whether
977n/a it will replace the previous function.
978n/a
979n/a Bind will return an identifier to allow deletion of the bound function with
980n/a unbind without memory leak.
981n/a
982n/a If FUNC or SEQUENCE is omitted the bound function or list
983n/a of bound events are returned."""
984n/a
9850 return self._bind(('bind', self._w), sequence, func, add)
9860 def unbind(self, sequence, funcid=None):
987n/a """Unbind for this widget for event SEQUENCE the
988n/a function identified with FUNCID."""
9890 self.tk.call('bind', self._w, sequence, '')
9900 if funcid:
9910 self.deletecommand(funcid)
9920 def bind_all(self, sequence=None, func=None, add=None):
993n/a """Bind to all widgets at an event SEQUENCE a call to function FUNC.
994n/a An additional boolean parameter ADD specifies whether FUNC will
995n/a be called additionally to the other bound function or whether
996n/a it will replace the previous function. See bind for the return value."""
9970 return self._bind(('bind', 'all'), sequence, func, add, 0)
9980 def unbind_all(self, sequence):
999n/a """Unbind for all widgets for event SEQUENCE all functions."""
10000 self.tk.call('bind', 'all' , sequence, '')
10010 def bind_class(self, className, sequence=None, func=None, add=None):
1002n/a
1003n/a """Bind to widgets with bindtag CLASSNAME at event
1004n/a SEQUENCE a call of function FUNC. An additional
1005n/a boolean parameter ADD specifies whether FUNC will be
1006n/a called additionally to the other bound function or
1007n/a whether it will replace the previous function. See bind for
1008n/a the return value."""
1009n/a
10100 return self._bind(('bind', className), sequence, func, add, 0)
10110 def unbind_class(self, className, sequence):
1012n/a """Unbind for a all widgets with bindtag CLASSNAME for event SEQUENCE
1013n/a all functions."""
10140 self.tk.call('bind', className , sequence, '')
10150 def mainloop(self, n=0):
1016n/a """Call the mainloop of Tk."""
10170 self.tk.mainloop(n)
10180 def quit(self):
1019n/a """Quit the Tcl interpreter. All widgets will be destroyed."""
10200 self.tk.quit()
10210 def _getints(self, string):
1022n/a """Internal function."""
10230 if string:
10240 return tuple(map(getint, self.tk.splitlist(string)))
10250 def _getdoubles(self, string):
1026n/a """Internal function."""
10270 if string:
10280 return tuple(map(getdouble, self.tk.splitlist(string)))
10290 def _getboolean(self, string):
1030n/a """Internal function."""
10310 if string:
10320 return self.tk.getboolean(string)
10330 def _displayof(self, displayof):
1034n/a """Internal function."""
10350 if displayof:
10360 return ('-displayof', displayof)
10370 if displayof is None:
10380 return ('-displayof', self._w)
10390 return ()
10400 def _options(self, cnf, kw = None):
1041n/a """Internal function."""
10420 if kw:
10430 cnf = _cnfmerge((cnf, kw))
1044n/a else:
10450 cnf = _cnfmerge(cnf)
10460 res = ()
10470 for k, v in cnf.items():
10480 if v is not None:
10490 if k[-1] == '_': k = k[:-1]
10500 if hasattr(v, '__call__'):
10510 v = self._register(v)
10520 elif isinstance(v, (tuple, list)):
10530 nv = []
10540 for item in v:
10550 if not isinstance(item, (basestring, int)):
10560 break
10570 elif isinstance(item, int):
10580 nv.append('%d' % item)
1059n/a else:
1060n/a # format it to proper Tcl code if it contains space
10610 nv.append(('{%s}' if ' ' in item else '%s') % item)
1062n/a else:
10630 v = ' '.join(nv)
10640 res = res + ('-'+k, v)
10650 return res
10660 def nametowidget(self, name):
1067n/a """Return the Tkinter instance of a widget identified by
1068n/a its Tcl name NAME."""
10690 name = str(name).split('.')
10700 w = self
1071n/a
10720 if not name[0]:
10730 w = w._root()
10740 name = name[1:]
1075n/a
10760 for n in name:
10770 if not n:
10780 break
10790 w = w.children[n]
1080n/a
10810 return w
10820 _nametowidget = nametowidget
10830 def _register(self, func, subst=None, needcleanup=1):
1084n/a """Return a newly created Tcl function. If this
1085n/a function is called, the Python function FUNC will
1086n/a be executed. An optional function SUBST can
1087n/a be given which will be executed before FUNC."""
10880 f = CallWrapper(func, subst, self).__call__
10890 name = repr(id(f))
10900 try:
10910 func = func.im_func
10920 except AttributeError:
10930 pass
10940 try:
10950 name = name + func.__name__
10960 except AttributeError:
10970 pass
10980 self.tk.createcommand(name, f)
10990 if needcleanup:
11000 if self._tclCommands is None:
11010 self._tclCommands = []
11020 self._tclCommands.append(name)
11030 return name
11040 register = _register
11050 def _root(self):
1106n/a """Internal function."""
11070 w = self
11080 while w.master: w = w.master
11090 return w
11100 _subst_format = ('%#', '%b', '%f', '%h', '%k',
11110 '%s', '%t', '%w', '%x', '%y',
11120 '%A', '%E', '%K', '%N', '%W', '%T', '%X', '%Y', '%D')
11130 _subst_format_str = " ".join(_subst_format)
11140 def _substitute(self, *args):
1115n/a """Internal function."""
11160 if len(args) != len(self._subst_format): return args
11170 getboolean = self.tk.getboolean
1118n/a
11190 getint = int
11200 def getint_event(s):
1121n/a """Tk changed behavior in 8.4.2, returning "??" rather more often."""
11220 try:
11230 return int(s)
11240 except ValueError:
11250 return s
1126n/a
11270 nsign, b, f, h, k, s, t, w, x, y, A, E, K, N, W, T, X, Y, D = args
1128n/a # Missing: (a, c, d, m, o, v, B, R)
11290 e = Event()
1130n/a # serial field: valid vor all events
1131n/a # number of button: ButtonPress and ButtonRelease events only
1132n/a # height field: Configure, ConfigureRequest, Create,
1133n/a # ResizeRequest, and Expose events only
1134n/a # keycode field: KeyPress and KeyRelease events only
1135n/a # time field: "valid for events that contain a time field"
1136n/a # width field: Configure, ConfigureRequest, Create, ResizeRequest,
1137n/a # and Expose events only
1138n/a # x field: "valid for events that contain a x field"
1139n/a # y field: "valid for events that contain a y field"
1140n/a # keysym as decimal: KeyPress and KeyRelease events only
1141n/a # x_root, y_root fields: ButtonPress, ButtonRelease, KeyPress,
1142n/a # KeyRelease,and Motion events
11430 e.serial = getint(nsign)
11440 e.num = getint_event(b)
11450 try: e.focus = getboolean(f)
11460 except TclError: pass
11470 e.height = getint_event(h)
11480 e.keycode = getint_event(k)
11490 e.state = getint_event(s)
11500 e.time = getint_event(t)
11510 e.width = getint_event(w)
11520 e.x = getint_event(x)
11530 e.y = getint_event(y)
11540 e.char = A
11550 try: e.send_event = getboolean(E)
11560 except TclError: pass
11570 e.keysym = K
11580 e.keysym_num = getint_event(N)
11590 e.type = T
11600 try:
11610 e.widget = self._nametowidget(W)
11620 except KeyError:
11630 e.widget = W
11640 e.x_root = getint_event(X)
11650 e.y_root = getint_event(Y)
11660 try:
11670 e.delta = getint(D)
11680 except ValueError:
11690 e.delta = 0
11700 return (e,)
11710 def _report_exception(self):
1172n/a """Internal function."""
11730 import sys
11740 exc, val, tb = sys.exc_type, sys.exc_value, sys.exc_traceback
11750 root = self._root()
11760 root.report_callback_exception(exc, val, tb)
11770 def _configure(self, cmd, cnf, kw):
1178n/a """Internal function."""
11790 if kw:
11800 cnf = _cnfmerge((cnf, kw))
11810 elif cnf:
11820 cnf = _cnfmerge(cnf)
11830 if cnf is None:
11840 cnf = {}
11850 for x in self.tk.split(
11860 self.tk.call(_flatten((self._w, cmd)))):
11870 cnf[x[0][1:]] = (x[0][1:],) + x[1:]
11880 return cnf
11890 if type(cnf) is StringType:
11900 x = self.tk.split(
11910 self.tk.call(_flatten((self._w, cmd, '-'+cnf))))
11920 return (x[0][1:],) + x[1:]
11930 self.tk.call(_flatten((self._w, cmd)) + self._options(cnf))
1194n/a # These used to be defined in Widget:
11950 def configure(self, cnf=None, **kw):
1196n/a """Configure resources of a widget.
1197n/a
1198n/a The values for resources are specified as keyword
1199n/a arguments. To get an overview about
1200n/a the allowed keyword arguments call the method keys.
1201n/a """
12020 return self._configure('configure', cnf, kw)
12030 config = configure
12040 def cget(self, key):
1205n/a """Return the resource value for a KEY given as string."""
12060 return self.tk.call(self._w, 'cget', '-' + key)
12070 __getitem__ = cget
12080 def __setitem__(self, key, value):
12090 self.configure({key: value})
12100 def __contains__(self, key):
12110 raise TypeError("Tkinter objects don't support 'in' tests.")
12120 def keys(self):
1213n/a """Return a list of all resource names of this widget."""
12140 return map(lambda x: x[0][1:],
12150 self.tk.split(self.tk.call(self._w, 'configure')))
12160 def __str__(self):
1217n/a """Return the window path name of this widget."""
12180 return self._w
1219n/a # Pack methods that apply to the master
12200 _noarg_ = ['_noarg_']
12210 def pack_propagate(self, flag=_noarg_):
1222n/a """Set or get the status for propagation of geometry information.
1223n/a
1224n/a A boolean argument specifies whether the geometry information
1225n/a of the slaves will determine the size of this widget. If no argument
1226n/a is given the current setting will be returned.
1227n/a """
12280 if flag is Misc._noarg_:
12290 return self._getboolean(self.tk.call(
12300 'pack', 'propagate', self._w))
1231n/a else:
12320 self.tk.call('pack', 'propagate', self._w, flag)
12330 propagate = pack_propagate
12340 def pack_slaves(self):
1235n/a """Return a list of all slaves of this widget
1236n/a in its packing order."""
12370 return map(self._nametowidget,
12380 self.tk.splitlist(
12390 self.tk.call('pack', 'slaves', self._w)))
12400 slaves = pack_slaves
1241n/a # Place method that applies to the master
12420 def place_slaves(self):
1243n/a """Return a list of all slaves of this widget
1244n/a in its packing order."""
12450 return map(self._nametowidget,
12460 self.tk.splitlist(
12470 self.tk.call(
12480 'place', 'slaves', self._w)))
1249n/a # Grid methods that apply to the master
12500 def grid_bbox(self, column=None, row=None, col2=None, row2=None):
1251n/a """Return a tuple of integer coordinates for the bounding
1252n/a box of this widget controlled by the geometry manager grid.
1253n/a
1254n/a If COLUMN, ROW is given the bounding box applies from
1255n/a the cell with row and column 0 to the specified
1256n/a cell. If COL2 and ROW2 are given the bounding box
1257n/a starts at that cell.
1258n/a
1259n/a The returned integers specify the offset of the upper left
1260n/a corner in the master widget and the width and height.
1261n/a """
12620 args = ('grid', 'bbox', self._w)
12630 if column is not None and row is not None:
12640 args = args + (column, row)
12650 if col2 is not None and row2 is not None:
12660 args = args + (col2, row2)
12670 return self._getints(self.tk.call(*args)) or None
1268n/a
12690 bbox = grid_bbox
12700 def _grid_configure(self, command, index, cnf, kw):
1271n/a """Internal function."""
12720 if type(cnf) is StringType and not kw:
12730 if cnf[-1:] == '_':
12740 cnf = cnf[:-1]
12750 if cnf[:1] != '-':
12760 cnf = '-'+cnf
12770 options = (cnf,)
1278n/a else:
12790 options = self._options(cnf, kw)
12800 if not options:
12810 res = self.tk.call('grid',
12820 command, self._w, index)
12830 words = self.tk.splitlist(res)
12840 dict = {}
12850 for i in range(0, len(words), 2):
12860 key = words[i][1:]
12870 value = words[i+1]
12880 if not value:
12890 value = None
12900 elif '.' in value:
12910 value = getdouble(value)
1292n/a else:
12930 value = getint(value)
12940 dict[key] = value
12950 return dict
12960 res = self.tk.call(
12970 ('grid', command, self._w, index)
12980 + options)
12990 if len(options) == 1:
13000 if not res: return None
1301n/a # In Tk 7.5, -width can be a float
13020 if '.' in res: return getdouble(res)
13030 return getint(res)
13040 def grid_columnconfigure(self, index, cnf={}, **kw):
1305n/a """Configure column INDEX of a grid.
1306n/a
1307n/a Valid resources are minsize (minimum size of the column),
1308n/a weight (how much does additional space propagate to this column)
1309n/a and pad (how much space to let additionally)."""
13100 return self._grid_configure('columnconfigure', index, cnf, kw)
13110 columnconfigure = grid_columnconfigure
13120 def grid_location(self, x, y):
1313n/a """Return a tuple of column and row which identify the cell
1314n/a at which the pixel at position X and Y inside the master
1315n/a widget is located."""
13160 return self._getints(
13170 self.tk.call(
13180 'grid', 'location', self._w, x, y)) or None
13190 def grid_propagate(self, flag=_noarg_):
1320n/a """Set or get the status for propagation of geometry information.
1321n/a
1322n/a A boolean argument specifies whether the geometry information
1323n/a of the slaves will determine the size of this widget. If no argument
1324n/a is given, the current setting will be returned.
1325n/a """
13260 if flag is Misc._noarg_:
13270 return self._getboolean(self.tk.call(
13280 'grid', 'propagate', self._w))
1329n/a else:
13300 self.tk.call('grid', 'propagate', self._w, flag)
13310 def grid_rowconfigure(self, index, cnf={}, **kw):
1332n/a """Configure row INDEX of a grid.
1333n/a
1334n/a Valid resources are minsize (minimum size of the row),
1335n/a weight (how much does additional space propagate to this row)
1336n/a and pad (how much space to let additionally)."""
13370 return self._grid_configure('rowconfigure', index, cnf, kw)
13380 rowconfigure = grid_rowconfigure
13390 def grid_size(self):
1340n/a """Return a tuple of the number of column and rows in the grid."""
13410 return self._getints(
13420 self.tk.call('grid', 'size', self._w)) or None
13430 size = grid_size
13440 def grid_slaves(self, row=None, column=None):
1345n/a """Return a list of all slaves of this widget
1346n/a in its packing order."""
13470 args = ()
13480 if row is not None:
13490 args = args + ('-row', row)
13500 if column is not None:
13510 args = args + ('-column', column)
13520 return map(self._nametowidget,
13530 self.tk.splitlist(self.tk.call(
13540 ('grid', 'slaves', self._w) + args)))
1355n/a
1356n/a # Support for the "event" command, new in Tk 4.2.
1357n/a # By Case Roole.
1358n/a
13590 def event_add(self, virtual, *sequences):
1360n/a """Bind a virtual event VIRTUAL (of the form <<Name>>)
1361n/a to an event SEQUENCE such that the virtual event is triggered
1362n/a whenever SEQUENCE occurs."""
13630 args = ('event', 'add', virtual) + sequences
13640 self.tk.call(args)
1365n/a
13660 def event_delete(self, virtual, *sequences):
1367n/a """Unbind a virtual event VIRTUAL from SEQUENCE."""
13680 args = ('event', 'delete', virtual) + sequences
13690 self.tk.call(args)
1370n/a
13710 def event_generate(self, sequence, **kw):
1372n/a """Generate an event SEQUENCE. Additional
1373n/a keyword arguments specify parameter of the event
1374n/a (e.g. x, y, rootx, rooty)."""
13750 args = ('event', 'generate', self._w, sequence)
13760 for k, v in kw.items():
13770 args = args + ('-%s' % k, str(v))
13780 self.tk.call(args)
1379n/a
13800 def event_info(self, virtual=None):
1381n/a """Return a list of all virtual events or the information
1382n/a about the SEQUENCE bound to the virtual event VIRTUAL."""
13830 return self.tk.splitlist(
13840 self.tk.call('event', 'info', virtual))
1385n/a
1386n/a # Image related commands
1387n/a
13880 def image_names(self):
1389n/a """Return a list of all existing image names."""
13900 return self.tk.call('image', 'names')
1391n/a
13920 def image_types(self):
1393n/a """Return a list of all available image types (e.g. phote bitmap)."""
13940 return self.tk.call('image', 'types')
1395n/a
1396n/a
13970class CallWrapper:
1398n/a """Internal class. Stores function to call when some user
1399n/a defined Tcl function is called e.g. after an event occurred."""
14000 def __init__(self, func, subst, widget):
1401n/a """Store FUNC, SUBST and WIDGET as members."""
14020 self.func = func
14030 self.subst = subst
14040 self.widget = widget
14050 def __call__(self, *args):
1406n/a """Apply first function SUBST to arguments, than FUNC."""
14070 try:
14080 if self.subst:
14090 args = self.subst(*args)
14100 return self.func(*args)
14110 except SystemExit, msg:
14120 raise SystemExit, msg
14130 except:
14140 self.widget._report_exception()
1415n/a
1416n/a
14170class XView:
1418n/a """Mix-in class for querying and changing the horizontal position
1419n/a of a widget's window."""
1420n/a
14210 def xview(self, *args):
1422n/a """Query and change the horizontal position of the view."""
14230 res = self.tk.call(self._w, 'xview', *args)
14240 if not args:
14250 return self._getdoubles(res)
1426n/a
14270 def xview_moveto(self, fraction):
1428n/a """Adjusts the view in the window so that FRACTION of the
1429n/a total width of the canvas is off-screen to the left."""
14300 self.tk.call(self._w, 'xview', 'moveto', fraction)
1431n/a
14320 def xview_scroll(self, number, what):
1433n/a """Shift the x-view according to NUMBER which is measured in "units"
1434n/a or "pages" (WHAT)."""
14350 self.tk.call(self._w, 'xview', 'scroll', number, what)
1436n/a
1437n/a
14380class YView:
1439n/a """Mix-in class for querying and changing the vertical position
1440n/a of a widget's window."""
1441n/a
14420 def yview(self, *args):
1443n/a """Query and change the vertical position of the view."""
14440 res = self.tk.call(self._w, 'yview', *args)
14450 if not args:
14460 return self._getdoubles(res)
1447n/a
14480 def yview_moveto(self, fraction):
1449n/a """Adjusts the view in the window so that FRACTION of the
1450n/a total height of the canvas is off-screen to the top."""
14510 self.tk.call(self._w, 'yview', 'moveto', fraction)
1452n/a
14530 def yview_scroll(self, number, what):
1454n/a """Shift the y-view according to NUMBER which is measured in
1455n/a "units" or "pages" (WHAT)."""
14560 self.tk.call(self._w, 'yview', 'scroll', number, what)
1457n/a
1458n/a
14590class Wm:
1460n/a """Provides functions for the communication with the window manager."""
1461n/a
1462n/a def wm_aspect(self,
14630 minNumer=None, minDenom=None,
14640 maxNumer=None, maxDenom=None):
1465n/a """Instruct the window manager to set the aspect ratio (width/height)
1466n/a of this widget to be between MINNUMER/MINDENOM and MAXNUMER/MAXDENOM. Return a tuple
1467n/a of the actual values if no argument is given."""
14680 return self._getints(
14690 self.tk.call('wm', 'aspect', self._w,
14700 minNumer, minDenom,
14710 maxNumer, maxDenom))
14720 aspect = wm_aspect
1473n/a
14740 def wm_attributes(self, *args):
1475n/a """This subcommand returns or sets platform specific attributes
1476n/a
1477n/a The first form returns a list of the platform specific flags and
1478n/a their values. The second form returns the value for the specific
1479n/a option. The third form sets one or more of the values. The values
1480n/a are as follows:
1481n/a
1482n/a On Windows, -disabled gets or sets whether the window is in a
1483n/a disabled state. -toolwindow gets or sets the style of the window
1484n/a to toolwindow (as defined in the MSDN). -topmost gets or sets
1485n/a whether this is a topmost window (displays above all other
1486n/a windows).
1487n/a
1488n/a On Macintosh, XXXXX
1489n/a
1490n/a On Unix, there are currently no special attribute values.
1491n/a """
14920 args = ('wm', 'attributes', self._w) + args
14930 return self.tk.call(args)
14940 attributes=wm_attributes
1495n/a
14960 def wm_client(self, name=None):
1497n/a """Store NAME in WM_CLIENT_MACHINE property of this widget. Return
1498n/a current value."""
14990 return self.tk.call('wm', 'client', self._w, name)
15000 client = wm_client
15010 def wm_colormapwindows(self, *wlist):
1502n/a """Store list of window names (WLIST) into WM_COLORMAPWINDOWS property
1503n/a of this widget. This list contains windows whose colormaps differ from their
1504n/a parents. Return current list of widgets if WLIST is empty."""
15050 if len(wlist) > 1:
15060 wlist = (wlist,) # Tk needs a list of windows here
15070 args = ('wm', 'colormapwindows', self._w) + wlist
15080 return map(self._nametowidget, self.tk.call(args))
15090 colormapwindows = wm_colormapwindows
15100 def wm_command(self, value=None):
1511n/a """Store VALUE in WM_COMMAND property. It is the command
1512n/a which shall be used to invoke the application. Return current
1513n/a command if VALUE is None."""
15140 return self.tk.call('wm', 'command', self._w, value)
15150 command = wm_command
15160 def wm_deiconify(self):
1517n/a """Deiconify this widget. If it was never mapped it will not be mapped.
1518n/a On Windows it will raise this widget and give it the focus."""
15190 return self.tk.call('wm', 'deiconify', self._w)
15200 deiconify = wm_deiconify
15210 def wm_focusmodel(self, model=None):
1522n/a """Set focus model to MODEL. "active" means that this widget will claim
1523n/a the focus itself, "passive" means that the window manager shall give
1524n/a the focus. Return current focus model if MODEL is None."""
15250 return self.tk.call('wm', 'focusmodel', self._w, model)
15260 focusmodel = wm_focusmodel
15270 def wm_frame(self):
1528n/a """Return identifier for decorative frame of this widget if present."""
15290 return self.tk.call('wm', 'frame', self._w)
15300 frame = wm_frame
15310 def wm_geometry(self, newGeometry=None):
1532n/a """Set geometry to NEWGEOMETRY of the form =widthxheight+x+y. Return
1533n/a current value if None is given."""
15340 return self.tk.call('wm', 'geometry', self._w, newGeometry)
15350 geometry = wm_geometry
1536n/a def wm_grid(self,
15370 baseWidth=None, baseHeight=None,
15380 widthInc=None, heightInc=None):
1539n/a """Instruct the window manager that this widget shall only be
1540n/a resized on grid boundaries. WIDTHINC and HEIGHTINC are the width and
1541n/a height of a grid unit in pixels. BASEWIDTH and BASEHEIGHT are the
1542n/a number of grid units requested in Tk_GeometryRequest."""
15430 return self._getints(self.tk.call(
15440 'wm', 'grid', self._w,
15450 baseWidth, baseHeight, widthInc, heightInc))
15460 grid = wm_grid
15470 def wm_group(self, pathName=None):
1548n/a """Set the group leader widgets for related widgets to PATHNAME. Return
1549n/a the group leader of this widget if None is given."""
15500 return self.tk.call('wm', 'group', self._w, pathName)
15510 group = wm_group
15520 def wm_iconbitmap(self, bitmap=None, default=None):
1553n/a """Set bitmap for the iconified widget to BITMAP. Return
1554n/a the bitmap if None is given.
1555n/a
1556n/a Under Windows, the DEFAULT parameter can be used to set the icon
1557n/a for the widget and any descendents that don't have an icon set
1558n/a explicitly. DEFAULT can be the relative path to a .ico file
1559n/a (example: root.iconbitmap(default='myicon.ico') ). See Tk
1560n/a documentation for more information."""
15610 if default:
15620 return self.tk.call('wm', 'iconbitmap', self._w, '-default', default)
1563n/a else:
15640 return self.tk.call('wm', 'iconbitmap', self._w, bitmap)
15650 iconbitmap = wm_iconbitmap
15660 def wm_iconify(self):
1567n/a """Display widget as icon."""
15680 return self.tk.call('wm', 'iconify', self._w)
15690 iconify = wm_iconify
15700 def wm_iconmask(self, bitmap=None):
1571n/a """Set mask for the icon bitmap of this widget. Return the
1572n/a mask if None is given."""
15730 return self.tk.call('wm', 'iconmask', self._w, bitmap)
15740 iconmask = wm_iconmask
15750 def wm_iconname(self, newName=None):
1576n/a """Set the name of the icon for this widget. Return the name if
1577n/a None is given."""
15780 return self.tk.call('wm', 'iconname', self._w, newName)
15790 iconname = wm_iconname
15800 def wm_iconposition(self, x=None, y=None):
1581n/a """Set the position of the icon of this widget to X and Y. Return
1582n/a a tuple of the current values of X and X if None is given."""
15830 return self._getints(self.tk.call(
15840 'wm', 'iconposition', self._w, x, y))
15850 iconposition = wm_iconposition
15860 def wm_iconwindow(self, pathName=None):
1587n/a """Set widget PATHNAME to be displayed instead of icon. Return the current
1588n/a value if None is given."""
15890 return self.tk.call('wm', 'iconwindow', self._w, pathName)
15900 iconwindow = wm_iconwindow
15910 def wm_maxsize(self, width=None, height=None):
1592n/a """Set max WIDTH and HEIGHT for this widget. If the window is gridded
1593n/a the values are given in grid units. Return the current values if None
1594n/a is given."""
15950 return self._getints(self.tk.call(
15960 'wm', 'maxsize', self._w, width, height))
15970 maxsize = wm_maxsize
15980 def wm_minsize(self, width=None, height=None):
1599n/a """Set min WIDTH and HEIGHT for this widget. If the window is gridded
1600n/a the values are given in grid units. Return the current values if None
1601n/a is given."""
16020 return self._getints(self.tk.call(
16030 'wm', 'minsize', self._w, width, height))
16040 minsize = wm_minsize
16050 def wm_overrideredirect(self, boolean=None):
1606n/a """Instruct the window manager to ignore this widget
1607n/a if BOOLEAN is given with 1. Return the current value if None
1608n/a is given."""
16090 return self._getboolean(self.tk.call(
16100 'wm', 'overrideredirect', self._w, boolean))
16110 overrideredirect = wm_overrideredirect
16120 def wm_positionfrom(self, who=None):
1613n/a """Instruct the window manager that the position of this widget shall
1614n/a be defined by the user if WHO is "user", and by its own policy if WHO is
1615n/a "program"."""
16160 return self.tk.call('wm', 'positionfrom', self._w, who)
16170 positionfrom = wm_positionfrom
16180 def wm_protocol(self, name=None, func=None):
1619n/a """Bind function FUNC to command NAME for this widget.
1620n/a Return the function bound to NAME if None is given. NAME could be
1621n/a e.g. "WM_SAVE_YOURSELF" or "WM_DELETE_WINDOW"."""
16220 if hasattr(func, '__call__'):
16230 command = self._register(func)
1624n/a else:
16250 command = func
16260 return self.tk.call(
16270 'wm', 'protocol', self._w, name, command)
16280 protocol = wm_protocol
16290 def wm_resizable(self, width=None, height=None):
1630n/a """Instruct the window manager whether this width can be resized
1631n/a in WIDTH or HEIGHT. Both values are boolean values."""
16320 return self.tk.call('wm', 'resizable', self._w, width, height)
16330 resizable = wm_resizable
16340 def wm_sizefrom(self, who=None):
1635n/a """Instruct the window manager that the size of this widget shall
1636n/a be defined by the user if WHO is "user", and by its own policy if WHO is
1637n/a "program"."""
16380 return self.tk.call('wm', 'sizefrom', self._w, who)
16390 sizefrom = wm_sizefrom
16400 def wm_state(self, newstate=None):
1641n/a """Query or set the state of this widget as one of normal, icon,
1642n/a iconic (see wm_iconwindow), withdrawn, or zoomed (Windows only)."""
16430 return self.tk.call('wm', 'state', self._w, newstate)
16440 state = wm_state
16450 def wm_title(self, string=None):
1646n/a """Set the title of this widget."""
16470 return self.tk.call('wm', 'title', self._w, string)
16480 title = wm_title
16490 def wm_transient(self, master=None):
1650n/a """Instruct the window manager that this widget is transient
1651n/a with regard to widget MASTER."""
16520 return self.tk.call('wm', 'transient', self._w, master)
16530 transient = wm_transient
16540 def wm_withdraw(self):
1655n/a """Withdraw this widget from the screen such that it is unmapped
1656n/a and forgotten by the window manager. Re-draw it with wm_deiconify."""
16570 return self.tk.call('wm', 'withdraw', self._w)
16580 withdraw = wm_withdraw
1659n/a
1660n/a
16610class Tk(Misc, Wm):
1662n/a """Toplevel widget of Tk which represents mostly the main window
1663n/a of an appliation. It has an associated Tcl interpreter."""
16640 _w = '.'
16650 def __init__(self, screenName=None, baseName=None, className='Tk',
16660 useTk=1, sync=0, use=None):
1667n/a """Return a new Toplevel widget on screen SCREENNAME. A new Tcl interpreter will
1668n/a be created. BASENAME will be used for the identification of the profile file (see
1669n/a readprofile).
1670n/a It is constructed from sys.argv[0] without extensions if None is given. CLASSNAME
1671n/a is the name of the widget class."""
16720 self.master = None
16730 self.children = {}
16740 self._tkloaded = 0
1675n/a # to avoid recursions in the getattr code in case of failure, we
1676n/a # ensure that self.tk is always _something_.
16770 self.tk = None
16780 if baseName is None:
16790 import sys, os
16800 baseName = os.path.basename(sys.argv[0])
16810 baseName, ext = os.path.splitext(baseName)
16820 if ext not in ('.py', '.pyc', '.pyo'):
16830 baseName = baseName + ext
16840 interactive = 0
16850 self.tk = _tkinter.create(screenName, baseName, className, interactive, wantobjects, useTk, sync, use)
16860 if useTk:
16870 self._loadtk()
16880 self.readprofile(baseName, className)
16890 def loadtk(self):
16900 if not self._tkloaded:
16910 self.tk.loadtk()
16920 self._loadtk()
16930 def _loadtk(self):
16940 self._tkloaded = 1
1695n/a global _default_root
1696n/a # Version sanity checks
16970 tk_version = self.tk.getvar('tk_version')
16980 if tk_version != _tkinter.TK_VERSION:
16990 raise RuntimeError, \
17000 "tk.h version (%s) doesn't match libtk.a version (%s)" \
17010 % (_tkinter.TK_VERSION, tk_version)
1702n/a # Under unknown circumstances, tcl_version gets coerced to float
17030 tcl_version = str(self.tk.getvar('tcl_version'))
17040 if tcl_version != _tkinter.TCL_VERSION:
17050 raise RuntimeError, \
17060 "tcl.h version (%s) doesn't match libtcl.a version (%s)" \
17070 % (_tkinter.TCL_VERSION, tcl_version)
17080 if TkVersion < 4.0:
17090 raise RuntimeError, \
17100 "Tk 4.0 or higher is required; found Tk %s" \
17110 % str(TkVersion)
1712n/a # Create and register the tkerror and exit commands
1713n/a # We need to inline parts of _register here, _ register
1714n/a # would register differently-named commands.
17150 if self._tclCommands is None:
17160 self._tclCommands = []
17170 self.tk.createcommand('tkerror', _tkerror)
17180 self.tk.createcommand('exit', _exit)
17190 self._tclCommands.append('tkerror')
17200 self._tclCommands.append('exit')
17210 if _support_default_root and not _default_root:
17220 _default_root = self
17230 self.protocol("WM_DELETE_WINDOW", self.destroy)
17240 def destroy(self):
1725n/a """Destroy this and all descendants widgets. This will
1726n/a end the application of this Tcl interpreter."""
17270 for c in self.children.values(): c.destroy()
17280 self.tk.call('destroy', self._w)
17290 Misc.destroy(self)
1730n/a global _default_root
17310 if _support_default_root and _default_root is self:
17320 _default_root = None
17330 def readprofile(self, baseName, className):
1734n/a """Internal function. It reads BASENAME.tcl and CLASSNAME.tcl into
1735n/a the Tcl Interpreter and calls execfile on BASENAME.py and CLASSNAME.py if
1736n/a such a file exists in the home directory."""
17370 import os
17380 if 'HOME' in os.environ: home = os.environ['HOME']
17390 else: home = os.curdir
17400 class_tcl = os.path.join(home, '.%s.tcl' % className)
17410 class_py = os.path.join(home, '.%s.py' % className)
17420 base_tcl = os.path.join(home, '.%s.tcl' % baseName)
17430 base_py = os.path.join(home, '.%s.py' % baseName)
17440 dir = {'self': self}
17450 exec 'from Tkinter import *' in dir
17460 if os.path.isfile(class_tcl):
17470 self.tk.call('source', class_tcl)
17480 if os.path.isfile(class_py):
17490 execfile(class_py, dir)
17500 if os.path.isfile(base_tcl):
17510 self.tk.call('source', base_tcl)
17520 if os.path.isfile(base_py):
17530 execfile(base_py, dir)
17540 def report_callback_exception(self, exc, val, tb):
1755n/a """Internal function. It reports exception on sys.stderr."""
17560 import traceback, sys
17570 sys.stderr.write("Exception in Tkinter callback\n")
17580 sys.last_type = exc
17590 sys.last_value = val
17600 sys.last_traceback = tb
17610 traceback.print_exception(exc, val, tb)
17620 def __getattr__(self, attr):
1763n/a "Delegate attribute access to the interpreter object"
17640 return getattr(self.tk, attr)
1765n/a
1766n/a# Ideally, the classes Pack, Place and Grid disappear, the
1767n/a# pack/place/grid methods are defined on the Widget class, and
1768n/a# everybody uses w.pack_whatever(...) instead of Pack.whatever(w,
1769n/a# ...), with pack(), place() and grid() being short for
1770n/a# pack_configure(), place_configure() and grid_columnconfigure(), and
1771n/a# forget() being short for pack_forget(). As a practical matter, I'm
1772n/a# afraid that there is too much code out there that may be using the
1773n/a# Pack, Place or Grid class, so I leave them intact -- but only as
1774n/a# backwards compatibility features. Also note that those methods that
1775n/a# take a master as argument (e.g. pack_propagate) have been moved to
1776n/a# the Misc class (which now incorporates all methods common between
1777n/a# toplevel and interior widgets). Again, for compatibility, these are
1778n/a# copied into the Pack, Place or Grid class.
1779n/a
1780n/a
17810def Tcl(screenName=None, baseName=None, className='Tk', useTk=0):
17820 return Tk(screenName, baseName, className, useTk)
1783n/a
17840class Pack:
1785n/a """Geometry manager Pack.
1786n/a
1787n/a Base class to use the methods pack_* in every widget."""
17880 def pack_configure(self, cnf={}, **kw):
1789n/a """Pack a widget in the parent widget. Use as options:
1790n/a after=widget - pack it after you have packed widget
1791n/a anchor=NSEW (or subset) - position widget according to
1792n/a given direction
1793n/a before=widget - pack it before you will pack widget
1794n/a expand=bool - expand widget if parent size grows
1795n/a fill=NONE or X or Y or BOTH - fill widget if widget grows
1796n/a in=master - use master to contain this widget
1797n/a in_=master - see 'in' option description
1798n/a ipadx=amount - add internal padding in x direction
1799n/a ipady=amount - add internal padding in y direction
1800n/a padx=amount - add padding in x direction
1801n/a pady=amount - add padding in y direction
1802n/a side=TOP or BOTTOM or LEFT or RIGHT - where to add this widget.
1803n/a """
18040 self.tk.call(
18050 ('pack', 'configure', self._w)
18060 + self._options(cnf, kw))
18070 pack = configure = config = pack_configure
18080 def pack_forget(self):
1809n/a """Unmap this widget and do not use it for the packing order."""
18100 self.tk.call('pack', 'forget', self._w)
18110 forget = pack_forget
18120 def pack_info(self):
1813n/a """Return information about the packing options
1814n/a for this widget."""
18150 words = self.tk.splitlist(
18160 self.tk.call('pack', 'info', self._w))
18170 dict = {}
18180 for i in range(0, len(words), 2):
18190 key = words[i][1:]
18200 value = words[i+1]
18210 if value[:1] == '.':
18220 value = self._nametowidget(value)
18230 dict[key] = value
18240 return dict
18250 info = pack_info
18260 propagate = pack_propagate = Misc.pack_propagate
18270 slaves = pack_slaves = Misc.pack_slaves
1828n/a
18290class Place:
1830n/a """Geometry manager Place.
1831n/a
1832n/a Base class to use the methods place_* in every widget."""
18330 def place_configure(self, cnf={}, **kw):
1834n/a """Place a widget in the parent widget. Use as options:
1835n/a in=master - master relative to which the widget is placed
1836n/a in_=master - see 'in' option description
1837n/a x=amount - locate anchor of this widget at position x of master
1838n/a y=amount - locate anchor of this widget at position y of master
1839n/a relx=amount - locate anchor of this widget between 0.0 and 1.0
1840n/a relative to width of master (1.0 is right edge)
1841n/a rely=amount - locate anchor of this widget between 0.0 and 1.0
1842n/a relative to height of master (1.0 is bottom edge)
1843n/a anchor=NSEW (or subset) - position anchor according to given direction
1844n/a width=amount - width of this widget in pixel
1845n/a height=amount - height of this widget in pixel
1846n/a relwidth=amount - width of this widget between 0.0 and 1.0
1847n/a relative to width of master (1.0 is the same width
1848n/a as the master)
1849n/a relheight=amount - height of this widget between 0.0 and 1.0
1850n/a relative to height of master (1.0 is the same
1851n/a height as the master)
1852n/a bordermode="inside" or "outside" - whether to take border width of
1853n/a master widget into account
1854n/a """
18550 self.tk.call(
18560 ('place', 'configure', self._w)
18570 + self._options(cnf, kw))
18580 place = configure = config = place_configure
18590 def place_forget(self):
1860n/a """Unmap this widget."""
18610 self.tk.call('place', 'forget', self._w)
18620 forget = place_forget
18630 def place_info(self):
1864n/a """Return information about the placing options
1865n/a for this widget."""
18660 words = self.tk.splitlist(
18670 self.tk.call('place', 'info', self._w))
18680 dict = {}
18690 for i in range(0, len(words), 2):
18700 key = words[i][1:]
18710 value = words[i+1]
18720 if value[:1] == '.':
18730 value = self._nametowidget(value)
18740 dict[key] = value
18750 return dict
18760 info = place_info
18770 slaves = place_slaves = Misc.place_slaves
1878n/a
18790class Grid:
1880n/a """Geometry manager Grid.
1881n/a
1882n/a Base class to use the methods grid_* in every widget."""
1883n/a # Thanks to Masazumi Yoshikawa (yosikawa@isi.edu)
18840 def grid_configure(self, cnf={}, **kw):
1885n/a """Position a widget in the parent widget in a grid. Use as options:
1886n/a column=number - use cell identified with given column (starting with 0)
1887n/a columnspan=number - this widget will span several columns
1888n/a in=master - use master to contain this widget
1889n/a in_=master - see 'in' option description
1890n/a ipadx=amount - add internal padding in x direction
1891n/a ipady=amount - add internal padding in y direction
1892n/a padx=amount - add padding in x direction
1893n/a pady=amount - add padding in y direction
1894n/a row=number - use cell identified with given row (starting with 0)
1895n/a rowspan=number - this widget will span several rows
1896n/a sticky=NSEW - if cell is larger on which sides will this
1897n/a widget stick to the cell boundary
1898n/a """
18990 self.tk.call(
19000 ('grid', 'configure', self._w)
19010 + self._options(cnf, kw))
19020 grid = configure = config = grid_configure
19030 bbox = grid_bbox = Misc.grid_bbox
19040 columnconfigure = grid_columnconfigure = Misc.grid_columnconfigure
19050 def grid_forget(self):
1906n/a """Unmap this widget."""
19070 self.tk.call('grid', 'forget', self._w)
19080 forget = grid_forget
19090 def grid_remove(self):
1910n/a """Unmap this widget but remember the grid options."""
19110 self.tk.call('grid', 'remove', self._w)
19120 def grid_info(self):
1913n/a """Return information about the options
1914n/a for positioning this widget in a grid."""
19150 words = self.tk.splitlist(
19160 self.tk.call('grid', 'info', self._w))
19170 dict = {}
19180 for i in range(0, len(words), 2):
19190 key = words[i][1:]
19200 value = words[i+1]
19210 if value[:1] == '.':
19220 value = self._nametowidget(value)
19230 dict[key] = value
19240 return dict
19250 info = grid_info
19260 location = grid_location = Misc.grid_location
19270 propagate = grid_propagate = Misc.grid_propagate
19280 rowconfigure = grid_rowconfigure = Misc.grid_rowconfigure
19290 size = grid_size = Misc.grid_size
19300 slaves = grid_slaves = Misc.grid_slaves
1931n/a
19320class BaseWidget(Misc):
1933n/a """Internal class."""
19340 def _setup(self, master, cnf):
1935n/a """Internal function. Sets up information about children."""
19360 if _support_default_root:
1937n/a global _default_root
19380 if not master:
19390 if not _default_root:
19400 _default_root = Tk()
19410 master = _default_root
19420 self.master = master
19430 self.tk = master.tk
19440 name = None
19450 if 'name' in cnf:
19460 name = cnf['name']
19470 del cnf['name']
19480 if not name:
19490 name = repr(id(self))
19500 self._name = name
19510 if master._w=='.':
19520 self._w = '.' + name
1953n/a else:
19540 self._w = master._w + '.' + name
19550 self.children = {}
19560 if self._name in self.master.children:
19570 self.master.children[self._name].destroy()
19580 self.master.children[self._name] = self
19590 def __init__(self, master, widgetName, cnf={}, kw={}, extra=()):
1960n/a """Construct a widget with the parent widget MASTER, a name WIDGETNAME
1961n/a and appropriate options."""
19620 if kw:
19630 cnf = _cnfmerge((cnf, kw))
19640 self.widgetName = widgetName
19650 BaseWidget._setup(self, master, cnf)
19660 if self._tclCommands is None:
19670 self._tclCommands = []
19680 classes = []
19690 for k in cnf.keys():
19700 if type(k) is ClassType:
19710 classes.append((k, cnf[k]))
19720 del cnf[k]
19730 self.tk.call(
19740 (widgetName, self._w) + extra + self._options(cnf))
19750 for k, v in classes:
19760 k.configure(self, v)
19770 def destroy(self):
1978n/a """Destroy this and all descendants widgets."""
19790 for c in self.children.values(): c.destroy()
19800 self.tk.call('destroy', self._w)
19810 if self._name in self.master.children:
19820 del self.master.children[self._name]
19830 Misc.destroy(self)
19840 def _do(self, name, args=()):
1985n/a # XXX Obsolete -- better use self.tk.call directly!
19860 return self.tk.call((self._w, name) + args)
1987n/a
19880class Widget(BaseWidget, Pack, Place, Grid):
1989n/a """Internal class.
1990n/a
1991n/a Base class for a widget which can be positioned with the geometry managers
1992n/a Pack, Place or Grid."""
19930 pass
1994n/a
19950class Toplevel(BaseWidget, Wm):
1996n/a """Toplevel widget, e.g. for dialogs."""
19970 def __init__(self, master=None, cnf={}, **kw):
1998n/a """Construct a toplevel widget with the parent MASTER.
1999n/a
2000n/a Valid resource names: background, bd, bg, borderwidth, class,
2001n/a colormap, container, cursor, height, highlightbackground,
2002n/a highlightcolor, highlightthickness, menu, relief, screen, takefocus,
2003n/a use, visual, width."""
20040 if kw:
20050 cnf = _cnfmerge((cnf, kw))
20060 extra = ()
20070 for wmkey in ['screen', 'class_', 'class', 'visual',
20080 'colormap']:
20090 if wmkey in cnf:
20100 val = cnf[wmkey]
2011n/a # TBD: a hack needed because some keys
2012n/a # are not valid as keyword arguments
20130 if wmkey[-1] == '_': opt = '-'+wmkey[:-1]
20140 else: opt = '-'+wmkey
20150 extra = extra + (opt, val)
20160 del cnf[wmkey]
20170 BaseWidget.__init__(self, master, 'toplevel', cnf, {}, extra)
20180 root = self._root()
20190 self.iconname(root.iconname())
20200 self.title(root.title())
20210 self.protocol("WM_DELETE_WINDOW", self.destroy)
2022n/a
20230class Button(Widget):
2024n/a """Button widget."""
20250 def __init__(self, master=None, cnf={}, **kw):
2026n/a """Construct a button widget with the parent MASTER.
2027n/a
2028n/a STANDARD OPTIONS
2029n/a
2030n/a activebackground, activeforeground, anchor,
2031n/a background, bitmap, borderwidth, cursor,
2032n/a disabledforeground, font, foreground
2033n/a highlightbackground, highlightcolor,
2034n/a highlightthickness, image, justify,
2035n/a padx, pady, relief, repeatdelay,
2036n/a repeatinterval, takefocus, text,
2037n/a textvariable, underline, wraplength
2038n/a
2039n/a WIDGET-SPECIFIC OPTIONS
2040n/a
2041n/a command, compound, default, height,
2042n/a overrelief, state, width
2043n/a """
20440 Widget.__init__(self, master, 'button', cnf, kw)
2045n/a
20460 def tkButtonEnter(self, *dummy):
20470 self.tk.call('tkButtonEnter', self._w)
2048n/a
20490 def tkButtonLeave(self, *dummy):
20500 self.tk.call('tkButtonLeave', self._w)
2051n/a
20520 def tkButtonDown(self, *dummy):
20530 self.tk.call('tkButtonDown', self._w)
2054n/a
20550 def tkButtonUp(self, *dummy):
20560 self.tk.call('tkButtonUp', self._w)
2057n/a
20580 def tkButtonInvoke(self, *dummy):
20590 self.tk.call('tkButtonInvoke', self._w)
2060n/a
20610 def flash(self):
2062n/a """Flash the button.
2063n/a
2064n/a This is accomplished by redisplaying
2065n/a the button several times, alternating between active and
2066n/a normal colors. At the end of the flash the button is left
2067n/a in the same normal/active state as when the command was
2068n/a invoked. This command is ignored if the button's state is
2069n/a disabled.
2070n/a """
20710 self.tk.call(self._w, 'flash')
2072n/a
20730 def invoke(self):
2074n/a """Invoke the command associated with the button.
2075n/a
2076n/a The return value is the return value from the command,
2077n/a or an empty string if there is no command associated with
2078n/a the button. This command is ignored if the button's state
2079n/a is disabled.
2080n/a """
20810 return self.tk.call(self._w, 'invoke')
2082n/a
2083n/a# Indices:
2084n/a# XXX I don't like these -- take them away
20850def AtEnd():
20860 return 'end'
20870def AtInsert(*args):
20880 s = 'insert'
20890 for a in args:
20900 if a: s = s + (' ' + a)
20910 return s
20920def AtSelFirst():
20930 return 'sel.first'
20940def AtSelLast():
20950 return 'sel.last'
20960def At(x, y=None):
20970 if y is None:
20980 return '@%r' % (x,)
2099n/a else:
21000 return '@%r,%r' % (x, y)
2101n/a
21020class Canvas(Widget, XView, YView):
2103n/a """Canvas widget to display graphical elements like lines or text."""
21040 def __init__(self, master=None, cnf={}, **kw):
2105n/a """Construct a canvas widget with the parent MASTER.
2106n/a
2107n/a Valid resource names: background, bd, bg, borderwidth, closeenough,
2108n/a confine, cursor, height, highlightbackground, highlightcolor,
2109n/a highlightthickness, insertbackground, insertborderwidth,
2110n/a insertofftime, insertontime, insertwidth, offset, relief,
2111n/a scrollregion, selectbackground, selectborderwidth, selectforeground,
2112n/a state, takefocus, width, xscrollcommand, xscrollincrement,
2113n/a yscrollcommand, yscrollincrement."""
21140 Widget.__init__(self, master, 'canvas', cnf, kw)
21150 def addtag(self, *args):
2116n/a """Internal function."""
21170 self.tk.call((self._w, 'addtag') + args)
21180 def addtag_above(self, newtag, tagOrId):
2119n/a """Add tag NEWTAG to all items above TAGORID."""
21200 self.addtag(newtag, 'above', tagOrId)
21210 def addtag_all(self, newtag):
2122n/a """Add tag NEWTAG to all items."""
21230 self.addtag(newtag, 'all')
21240 def addtag_below(self, newtag, tagOrId):
2125n/a """Add tag NEWTAG to all items below TAGORID."""
21260 self.addtag(newtag, 'below', tagOrId)
21270 def addtag_closest(self, newtag, x, y, halo=None, start=None):
2128n/a """Add tag NEWTAG to item which is closest to pixel at X, Y.
2129n/a If several match take the top-most.
2130n/a All items closer than HALO are considered overlapping (all are
2131n/a closests). If START is specified the next below this tag is taken."""
21320 self.addtag(newtag, 'closest', x, y, halo, start)
21330 def addtag_enclosed(self, newtag, x1, y1, x2, y2):
2134n/a """Add tag NEWTAG to all items in the rectangle defined
2135n/a by X1,Y1,X2,Y2."""
21360 self.addtag(newtag, 'enclosed', x1, y1, x2, y2)
21370 def addtag_overlapping(self, newtag, x1, y1, x2, y2):
2138n/a """Add tag NEWTAG to all items which overlap the rectangle
2139n/a defined by X1,Y1,X2,Y2."""
21400 self.addtag(newtag, 'overlapping', x1, y1, x2, y2)
21410 def addtag_withtag(self, newtag, tagOrId):
2142n/a """Add tag NEWTAG to all items with TAGORID."""
21430 self.addtag(newtag, 'withtag', tagOrId)
21440 def bbox(self, *args):
2145n/a """Return a tuple of X1,Y1,X2,Y2 coordinates for a rectangle
2146n/a which encloses all items with tags specified as arguments."""
21470 return self._getints(
21480 self.tk.call((self._w, 'bbox') + args)) or None
21490 def tag_unbind(self, tagOrId, sequence, funcid=None):
2150n/a """Unbind for all items with TAGORID for event SEQUENCE the
2151n/a function identified with FUNCID."""
21520 self.tk.call(self._w, 'bind', tagOrId, sequence, '')
21530 if funcid:
21540 self.deletecommand(funcid)
21550 def tag_bind(self, tagOrId, sequence=None, func=None, add=None):
2156n/a """Bind to all items with TAGORID at event SEQUENCE a call to function FUNC.
2157n/a
2158n/a An additional boolean parameter ADD specifies whether FUNC will be
2159n/a called additionally to the other bound function or whether it will
2160n/a replace the previous function. See bind for the return value."""
21610 return self._bind((self._w, 'bind', tagOrId),
21620 sequence, func, add)
21630 def canvasx(self, screenx, gridspacing=None):
2164n/a """Return the canvas x coordinate of pixel position SCREENX rounded
2165n/a to nearest multiple of GRIDSPACING units."""
21660 return getdouble(self.tk.call(
21670 self._w, 'canvasx', screenx, gridspacing))
21680 def canvasy(self, screeny, gridspacing=None):
2169n/a """Return the canvas y coordinate of pixel position SCREENY rounded
2170n/a to nearest multiple of GRIDSPACING units."""
21710 return getdouble(self.tk.call(
21720 self._w, 'canvasy', screeny, gridspacing))
21730 def coords(self, *args):
2174n/a """Return a list of coordinates for the item given in ARGS."""
2175n/a # XXX Should use _flatten on args
21760 return map(getdouble,
21770 self.tk.splitlist(
21780 self.tk.call((self._w, 'coords') + args)))
21790 def _create(self, itemType, args, kw): # Args: (val, val, ..., cnf={})
2180n/a """Internal function."""
21810 args = _flatten(args)
21820 cnf = args[-1]
21830 if type(cnf) in (DictionaryType, TupleType):
21840 args = args[:-1]
2185n/a else:
21860 cnf = {}
21870 return getint(self.tk.call(
21880 self._w, 'create', itemType,
21890 *(args + self._options(cnf, kw))))
21900 def create_arc(self, *args, **kw):
2191n/a """Create arc shaped region with coordinates x1,y1,x2,y2."""
21920 return self._create('arc', args, kw)
21930 def create_bitmap(self, *args, **kw):
2194n/a """Create bitmap with coordinates x1,y1."""
21950 return self._create('bitmap', args, kw)
21960 def create_image(self, *args, **kw):
2197n/a """Create image item with coordinates x1,y1."""
21980 return self._create('image', args, kw)
21990 def create_line(self, *args, **kw):
2200n/a """Create line with coordinates x1,y1,...,xn,yn."""
22010 return self._create('line', args, kw)
22020 def create_oval(self, *args, **kw):
2203n/a """Create oval with coordinates x1,y1,x2,y2."""
22040 return self._create('oval', args, kw)
22050 def create_polygon(self, *args, **kw):
2206n/a """Create polygon with coordinates x1,y1,...,xn,yn."""
22070 return self._create('polygon', args, kw)
22080 def create_rectangle(self, *args, **kw):
2209n/a """Create rectangle with coordinates x1,y1,x2,y2."""
22100 return self._create('rectangle', args, kw)
22110 def create_text(self, *args, **kw):
2212n/a """Create text with coordinates x1,y1."""
22130 return self._create('text', args, kw)
22140 def create_window(self, *args, **kw):
2215n/a """Create window with coordinates x1,y1,x2,y2."""
22160 return self._create('window', args, kw)
22170 def dchars(self, *args):
2218n/a """Delete characters of text items identified by tag or id in ARGS (possibly
2219n/a several times) from FIRST to LAST character (including)."""
22200 self.tk.call((self._w, 'dchars') + args)
22210 def delete(self, *args):
2222n/a """Delete items identified by all tag or ids contained in ARGS."""
22230 self.tk.call((self._w, 'delete') + args)
22240 def dtag(self, *args):
2225n/a """Delete tag or id given as last arguments in ARGS from items
2226n/a identified by first argument in ARGS."""
22270 self.tk.call((self._w, 'dtag') + args)
22280 def find(self, *args):
2229n/a """Internal function."""
22300 return self._getints(
22310 self.tk.call((self._w, 'find') + args)) or ()
22320 def find_above(self, tagOrId):
2233n/a """Return items above TAGORID."""
22340 return self.find('above', tagOrId)
22350 def find_all(self):
2236n/a """Return all items."""
22370 return self.find('all')
22380 def find_below(self, tagOrId):
2239n/a """Return all items below TAGORID."""
22400 return self.find('below', tagOrId)
22410 def find_closest(self, x, y, halo=None, start=None):
2242n/a """Return item which is closest to pixel at X, Y.
2243n/a If several match take the top-most.
2244n/a All items closer than HALO are considered overlapping (all are
2245n/a closests). If START is specified the next below this tag is taken."""
22460 return self.find('closest', x, y, halo, start)
22470 def find_enclosed(self, x1, y1, x2, y2):
2248n/a """Return all items in rectangle defined
2249n/a by X1,Y1,X2,Y2."""
22500 return self.find('enclosed', x1, y1, x2, y2)
22510 def find_overlapping(self, x1, y1, x2, y2):
2252n/a """Return all items which overlap the rectangle
2253n/a defined by X1,Y1,X2,Y2."""
22540 return self.find('overlapping', x1, y1, x2, y2)
22550 def find_withtag(self, tagOrId):
2256n/a """Return all items with TAGORID."""
22570 return self.find('withtag', tagOrId)
22580 def focus(self, *args):
2259n/a """Set focus to the first item specified in ARGS."""
22600 return self.tk.call((self._w, 'focus') + args)
22610 def gettags(self, *args):
2262n/a """Return tags associated with the first item specified in ARGS."""
22630 return self.tk.splitlist(
22640 self.tk.call((self._w, 'gettags') + args))
22650 def icursor(self, *args):
2266n/a """Set cursor at position POS in the item identified by TAGORID.
2267n/a In ARGS TAGORID must be first."""
22680 self.tk.call((self._w, 'icursor') + args)
22690 def index(self, *args):
2270n/a """Return position of cursor as integer in item specified in ARGS."""
22710 return getint(self.tk.call((self._w, 'index') + args))
22720 def insert(self, *args):
2273n/a """Insert TEXT in item TAGORID at position POS. ARGS must
2274n/a be TAGORID POS TEXT."""
22750 self.tk.call((self._w, 'insert') + args)
22760 def itemcget(self, tagOrId, option):
2277n/a """Return the resource value for an OPTION for item TAGORID."""
22780 return self.tk.call(
22790 (self._w, 'itemcget') + (tagOrId, '-'+option))
22800 def itemconfigure(self, tagOrId, cnf=None, **kw):
2281n/a """Configure resources of an item TAGORID.
2282n/a
2283n/a The values for resources are specified as keyword
2284n/a arguments. To get an overview about
2285n/a the allowed keyword arguments call the method without arguments.
2286n/a """
22870 return self._configure(('itemconfigure', tagOrId), cnf, kw)
22880 itemconfig = itemconfigure
2289n/a # lower, tkraise/lift hide Misc.lower, Misc.tkraise/lift,
2290n/a # so the preferred name for them is tag_lower, tag_raise
2291n/a # (similar to tag_bind, and similar to the Text widget);
2292n/a # unfortunately can't delete the old ones yet (maybe in 1.6)
22930 def tag_lower(self, *args):
2294n/a """Lower an item TAGORID given in ARGS
2295n/a (optional below another item)."""
22960 self.tk.call((self._w, 'lower') + args)
22970 lower = tag_lower
22980 def move(self, *args):
2299n/a """Move an item TAGORID given in ARGS."""
23000 self.tk.call((self._w, 'move') + args)
23010 def postscript(self, cnf={}, **kw):
2302n/a """Print the contents of the canvas to a postscript
2303n/a file. Valid options: colormap, colormode, file, fontmap,
2304n/a height, pageanchor, pageheight, pagewidth, pagex, pagey,
2305n/a rotate, witdh, x, y."""
23060 return self.tk.call((self._w, 'postscript') +
23070 self._options(cnf, kw))
23080 def tag_raise(self, *args):
2309n/a """Raise an item TAGORID given in ARGS
2310n/a (optional above another item)."""
23110 self.tk.call((self._w, 'raise') + args)
23120 lift = tkraise = tag_raise
23130 def scale(self, *args):
2314n/a """Scale item TAGORID with XORIGIN, YORIGIN, XSCALE, YSCALE."""
23150 self.tk.call((self._w, 'scale') + args)
23160 def scan_mark(self, x, y):
2317n/a """Remember the current X, Y coordinates."""
23180 self.tk.call(self._w, 'scan', 'mark', x, y)
23190 def scan_dragto(self, x, y, gain=10):
2320n/a """Adjust the view of the canvas to GAIN times the
2321n/a difference between X and Y and the coordinates given in
2322n/a scan_mark."""
23230 self.tk.call(self._w, 'scan', 'dragto', x, y, gain)
23240 def select_adjust(self, tagOrId, index):
2325n/a """Adjust the end of the selection near the cursor of an item TAGORID to index."""
23260 self.tk.call(self._w, 'select', 'adjust', tagOrId, index)
23270 def select_clear(self):
2328n/a """Clear the selection if it is in this widget."""
23290 self.tk.call(self._w, 'select', 'clear')
23300 def select_from(self, tagOrId, index):
2331n/a """Set the fixed end of a selection in item TAGORID to INDEX."""
23320 self.tk.call(self._w, 'select', 'from', tagOrId, index)
23330 def select_item(self):
2334n/a """Return the item which has the selection."""
23350 return self.tk.call(self._w, 'select', 'item') or None
23360 def select_to(self, tagOrId, index):
2337n/a """Set the variable end of a selection in item TAGORID to INDEX."""
23380 self.tk.call(self._w, 'select', 'to', tagOrId, index)
23390 def type(self, tagOrId):
2340n/a """Return the type of the item TAGORID."""
23410 return self.tk.call(self._w, 'type', tagOrId) or None
2342n/a
23430class Checkbutton(Widget):
2344n/a """Checkbutton widget which is either in on- or off-state."""
23450 def __init__(self, master=None, cnf={}, **kw):
2346n/a """Construct a checkbutton widget with the parent MASTER.
2347n/a
2348n/a Valid resource names: activebackground, activeforeground, anchor,
2349n/a background, bd, bg, bitmap, borderwidth, command, cursor,
2350n/a disabledforeground, fg, font, foreground, height,
2351n/a highlightbackground, highlightcolor, highlightthickness, image,
2352n/a indicatoron, justify, offvalue, onvalue, padx, pady, relief,
2353n/a selectcolor, selectimage, state, takefocus, text, textvariable,
2354n/a underline, variable, width, wraplength."""
23550 Widget.__init__(self, master, 'checkbutton', cnf, kw)
23560 def deselect(self):
2357n/a """Put the button in off-state."""
23580 self.tk.call(self._w, 'deselect')
23590 def flash(self):
2360n/a """Flash the button."""
23610 self.tk.call(self._w, 'flash')
23620 def invoke(self):
2363n/a """Toggle the button and invoke a command if given as resource."""
23640 return self.tk.call(self._w, 'invoke')
23650 def select(self):
2366n/a """Put the button in on-state."""
23670 self.tk.call(self._w, 'select')
23680 def toggle(self):
2369n/a """Toggle the button."""
23700 self.tk.call(self._w, 'toggle')
2371n/a
23720class Entry(Widget, XView):
2373n/a """Entry widget which allows to display simple text."""
23740 def __init__(self, master=None, cnf={}, **kw):
2375n/a """Construct an entry widget with the parent MASTER.
2376n/a
2377n/a Valid resource names: background, bd, bg, borderwidth, cursor,
2378n/a exportselection, fg, font, foreground, highlightbackground,
2379n/a highlightcolor, highlightthickness, insertbackground,
2380n/a insertborderwidth, insertofftime, insertontime, insertwidth,
2381n/a invalidcommand, invcmd, justify, relief, selectbackground,
2382n/a selectborderwidth, selectforeground, show, state, takefocus,
2383n/a textvariable, validate, validatecommand, vcmd, width,
2384n/a xscrollcommand."""
23850 Widget.__init__(self, master, 'entry', cnf, kw)
23860 def delete(self, first, last=None):
2387n/a """Delete text from FIRST to LAST (not included)."""
23880 self.tk.call(self._w, 'delete', first, last)
23890 def get(self):
2390n/a """Return the text."""
23910 return self.tk.call(self._w, 'get')
23920 def icursor(self, index):
2393n/a """Insert cursor at INDEX."""
23940 self.tk.call(self._w, 'icursor', index)
23950 def index(self, index):
2396n/a """Return position of cursor."""
23970 return getint(self.tk.call(
23980 self._w, 'index', index))
23990 def insert(self, index, string):
2400n/a """Insert STRING at INDEX."""
24010 self.tk.call(self._w, 'insert', index, string)
24020 def scan_mark(self, x):
2403n/a """Remember the current X, Y coordinates."""
24040 self.tk.call(self._w, 'scan', 'mark', x)
24050 def scan_dragto(self, x):
2406n/a """Adjust the view of the canvas to 10 times the
2407n/a difference between X and Y and the coordinates given in
2408n/a scan_mark."""
24090 self.tk.call(self._w, 'scan', 'dragto', x)
24100 def selection_adjust(self, index):
2411n/a """Adjust the end of the selection near the cursor to INDEX."""
24120 self.tk.call(self._w, 'selection', 'adjust', index)
24130 select_adjust = selection_adjust
24140 def selection_clear(self):
2415n/a """Clear the selection if it is in this widget."""
24160 self.tk.call(self._w, 'selection', 'clear')
24170 select_clear = selection_clear
24180 def selection_from(self, index):
2419n/a """Set the fixed end of a selection to INDEX."""
24200 self.tk.call(self._w, 'selection', 'from', index)
24210 select_from = selection_from
24220 def selection_present(self):
2423n/a """Return True if there are characters selected in the entry, False
2424n/a otherwise."""
24250 return self.tk.getboolean(
24260 self.tk.call(self._w, 'selection', 'present'))
24270 select_present = selection_present
24280 def selection_range(self, start, end):
2429n/a """Set the selection from START to END (not included)."""
24300 self.tk.call(self._w, 'selection', 'range', start, end)
24310 select_range = selection_range
24320 def selection_to(self, index):
2433n/a """Set the variable end of a selection to INDEX."""
24340 self.tk.call(self._w, 'selection', 'to', index)
24350 select_to = selection_to
2436n/a
24370class Frame(Widget):
2438n/a """Frame widget which may contain other widgets and can have a 3D border."""
24390 def __init__(self, master=None, cnf={}, **kw):
2440n/a """Construct a frame widget with the parent MASTER.
2441n/a
2442n/a Valid resource names: background, bd, bg, borderwidth, class,
2443n/a colormap, container, cursor, height, highlightbackground,
2444n/a highlightcolor, highlightthickness, relief, takefocus, visual, width."""
24450 cnf = _cnfmerge((cnf, kw))
24460 extra = ()
24470 if 'class_' in cnf:
24480 extra = ('-class', cnf['class_'])
24490 del cnf['class_']
24500 elif 'class' in cnf:
24510 extra = ('-class', cnf['class'])
24520 del cnf['class']
24530 Widget.__init__(self, master, 'frame', cnf, {}, extra)
2454n/a
24550class Label(Widget):
2456n/a """Label widget which can display text and bitmaps."""
24570 def __init__(self, master=None, cnf={}, **kw):
2458n/a """Construct a label widget with the parent MASTER.
2459n/a
2460n/a STANDARD OPTIONS
2461n/a
2462n/a activebackground, activeforeground, anchor,
2463n/a background, bitmap, borderwidth, cursor,
2464n/a disabledforeground, font, foreground,
2465n/a highlightbackground, highlightcolor,
2466n/a highlightthickness, image, justify,
2467n/a padx, pady, relief, takefocus, text,
2468n/a textvariable, underline, wraplength
2469n/a
2470n/a WIDGET-SPECIFIC OPTIONS
2471n/a
2472n/a height, state, width
2473n/a
2474n/a """
24750 Widget.__init__(self, master, 'label', cnf, kw)
2476n/a
24770class Listbox(Widget, XView, YView):
2478n/a """Listbox widget which can display a list of strings."""
24790 def __init__(self, master=None, cnf={}, **kw):
2480n/a """Construct a listbox widget with the parent MASTER.
2481n/a
2482n/a Valid resource names: background, bd, bg, borderwidth, cursor,
2483n/a exportselection, fg, font, foreground, height, highlightbackground,
2484n/a highlightcolor, highlightthickness, relief, selectbackground,
2485n/a selectborderwidth, selectforeground, selectmode, setgrid, takefocus,
2486n/a width, xscrollcommand, yscrollcommand, listvariable."""
24870 Widget.__init__(self, master, 'listbox', cnf, kw)
24880 def activate(self, index):
2489n/a """Activate item identified by INDEX."""
24900 self.tk.call(self._w, 'activate', index)
24910 def bbox(self, *args):
2492n/a """Return a tuple of X1,Y1,X2,Y2 coordinates for a rectangle
2493n/a which encloses the item identified by index in ARGS."""
24940 return self._getints(
24950 self.tk.call((self._w, 'bbox') + args)) or None
24960 def curselection(self):
2497n/a """Return list of indices of currently selected item."""
2498n/a # XXX Ought to apply self._getints()...
24990 return self.tk.splitlist(self.tk.call(
25000 self._w, 'curselection'))
25010 def delete(self, first, last=None):
2502n/a """Delete items from FIRST to LAST (not included)."""
25030 self.tk.call(self._w, 'delete', first, last)
25040 def get(self, first, last=None):
2505n/a """Get list of items from FIRST to LAST (not included)."""
25060 if last:
25070 return self.tk.splitlist(self.tk.call(
25080 self._w, 'get', first, last))
2509n/a else:
25100 return self.tk.call(self._w, 'get', first)
25110 def index(self, index):
2512n/a """Return index of item identified with INDEX."""
25130 i = self.tk.call(self._w, 'index', index)
25140 if i == 'none': return None
25150 return getint(i)
25160 def insert(self, index, *elements):
2517n/a """Insert ELEMENTS at INDEX."""
25180 self.tk.call((self._w, 'insert', index) + elements)
25190 def nearest(self, y):
2520n/a """Get index of item which is nearest to y coordinate Y."""
25210 return getint(self.tk.call(
25220 self._w, 'nearest', y))
25230 def scan_mark(self, x, y):
2524n/a """Remember the current X, Y coordinates."""
25250 self.tk.call(self._w, 'scan', 'mark', x, y)
25260 def scan_dragto(self, x, y):
2527n/a """Adjust the view of the listbox to 10 times the
2528n/a difference between X and Y and the coordinates given in
2529n/a scan_mark."""
25300 self.tk.call(self._w, 'scan', 'dragto', x, y)
25310 def see(self, index):
2532n/a """Scroll such that INDEX is visible."""
25330 self.tk.call(self._w, 'see', index)
25340 def selection_anchor(self, index):
2535n/a """Set the fixed end oft the selection to INDEX."""
25360 self.tk.call(self._w, 'selection', 'anchor', index)
25370 select_anchor = selection_anchor
25380 def selection_clear(self, first, last=None):
2539n/a """Clear the selection from FIRST to LAST (not included)."""
25400 self.tk.call(self._w,
25410 'selection', 'clear', first, last)
25420 select_clear = selection_clear
25430 def selection_includes(self, index):
2544n/a """Return 1 if INDEX is part of the selection."""
25450 return self.tk.getboolean(self.tk.call(
25460 self._w, 'selection', 'includes', index))
25470 select_includes = selection_includes
25480 def selection_set(self, first, last=None):
2549n/a """Set the selection from FIRST to LAST (not included) without
2550n/a changing the currently selected elements."""
25510 self.tk.call(self._w, 'selection', 'set', first, last)
25520 select_set = selection_set
25530 def size(self):
2554n/a """Return the number of elements in the listbox."""
25550 return getint(self.tk.call(self._w, 'size'))
25560 def itemcget(self, index, option):
2557n/a """Return the resource value for an ITEM and an OPTION."""
25580 return self.tk.call(
25590 (self._w, 'itemcget') + (index, '-'+option))
25600 def itemconfigure(self, index, cnf=None, **kw):
2561n/a """Configure resources of an ITEM.
2562n/a
2563n/a The values for resources are specified as keyword arguments.
2564n/a To get an overview about the allowed keyword arguments
2565n/a call the method without arguments.
2566n/a Valid resource names: background, bg, foreground, fg,
2567n/a selectbackground, selectforeground."""
25680 return self._configure(('itemconfigure', index), cnf, kw)
25690 itemconfig = itemconfigure
2570n/a
25710class Menu(Widget):
2572n/a """Menu widget which allows to display menu bars, pull-down menus and pop-up menus."""
25730 def __init__(self, master=None, cnf={}, **kw):
2574n/a """Construct menu widget with the parent MASTER.
2575n/a
2576n/a Valid resource names: activebackground, activeborderwidth,
2577n/a activeforeground, background, bd, bg, borderwidth, cursor,
2578n/a disabledforeground, fg, font, foreground, postcommand, relief,
2579n/a selectcolor, takefocus, tearoff, tearoffcommand, title, type."""
25800 Widget.__init__(self, master, 'menu', cnf, kw)
25810 def tk_bindForTraversal(self):
25820 pass # obsolete since Tk 4.0
25830 def tk_mbPost(self):
25840 self.tk.call('tk_mbPost', self._w)
25850 def tk_mbUnpost(self):
25860 self.tk.call('tk_mbUnpost')
25870 def tk_traverseToMenu(self, char):
25880 self.tk.call('tk_traverseToMenu', self._w, char)
25890 def tk_traverseWithinMenu(self, char):
25900 self.tk.call('tk_traverseWithinMenu', self._w, char)
25910 def tk_getMenuButtons(self):
25920 return self.tk.call('tk_getMenuButtons', self._w)
25930 def tk_nextMenu(self, count):
25940 self.tk.call('tk_nextMenu', count)
25950 def tk_nextMenuEntry(self, count):
25960 self.tk.call('tk_nextMenuEntry', count)
25970 def tk_invokeMenu(self):
25980 self.tk.call('tk_invokeMenu', self._w)
25990 def tk_firstMenu(self):
26000 self.tk.call('tk_firstMenu', self._w)
26010 def tk_mbButtonDown(self):
26020 self.tk.call('tk_mbButtonDown', self._w)
26030 def tk_popup(self, x, y, entry=""):
2604n/a """Post the menu at position X,Y with entry ENTRY."""
26050 self.tk.call('tk_popup', self._w, x, y, entry)
26060 def activate(self, index):
2607n/a """Activate entry at INDEX."""
26080 self.tk.call(self._w, 'activate', index)
26090 def add(self, itemType, cnf={}, **kw):
2610n/a """Internal function."""
26110 self.tk.call((self._w, 'add', itemType) +
26120 self._options(cnf, kw))
26130 def add_cascade(self, cnf={}, **kw):
2614n/a """Add hierarchical menu item."""
26150 self.add('cascade', cnf or kw)
26160 def add_checkbutton(self, cnf={}, **kw):
2617n/a """Add checkbutton menu item."""
26180 self.add('checkbutton', cnf or kw)
26190 def add_command(self, cnf={}, **kw):
2620n/a """Add command menu item."""
26210 self.add('command', cnf or kw)
26220 def add_radiobutton(self, cnf={}, **kw):
2623n/a """Addd radio menu item."""
26240 self.add('radiobutton', cnf or kw)
26250 def add_separator(self, cnf={}, **kw):
2626n/a """Add separator."""
26270 self.add('separator', cnf or kw)
26280 def insert(self, index, itemType, cnf={}, **kw):
2629n/a """Internal function."""
26300 self.tk.call((self._w, 'insert', index, itemType) +
26310 self._options(cnf, kw))
26320 def insert_cascade(self, index, cnf={}, **kw):
2633n/a """Add hierarchical menu item at INDEX."""
26340 self.insert(index, 'cascade', cnf or kw)
26350 def insert_checkbutton(self, index, cnf={}, **kw):
2636n/a """Add checkbutton menu item at INDEX."""
26370 self.insert(index, 'checkbutton', cnf or kw)
26380 def insert_command(self, index, cnf={}, **kw):
2639n/a """Add command menu item at INDEX."""
26400 self.insert(index, 'command', cnf or kw)
26410 def insert_radiobutton(self, index, cnf={}, **kw):
2642n/a """Addd radio menu item at INDEX."""
26430 self.insert(index, 'radiobutton', cnf or kw)
26440 def insert_separator(self, index, cnf={}, **kw):
2645n/a """Add separator at INDEX."""
26460 self.insert(index, 'separator', cnf or kw)
26470 def delete(self, index1, index2=None):
2648n/a """Delete menu items between INDEX1 and INDEX2 (included)."""
26490 if index2 is None:
26500 index2 = index1
2651n/a
26520 num_index1, num_index2 = self.index(index1), self.index(index2)
26530 if (num_index1 is None) or (num_index2 is None):
26540 num_index1, num_index2 = 0, -1
2655n/a
26560 for i in range(num_index1, num_index2 + 1):
26570 if 'command' in self.entryconfig(i):
26580 c = str(self.entrycget(i, 'command'))
26590 if c:
26600 self.deletecommand(c)
26610 self.tk.call(self._w, 'delete', index1, index2)
26620 def entrycget(self, index, option):
2663n/a """Return the resource value of an menu item for OPTION at INDEX."""
26640 return self.tk.call(self._w, 'entrycget', index, '-' + option)
26650 def entryconfigure(self, index, cnf=None, **kw):
2666n/a """Configure a menu item at INDEX."""
26670 return self._configure(('entryconfigure', index), cnf, kw)
26680 entryconfig = entryconfigure
26690 def index(self, index):
2670n/a """Return the index of a menu item identified by INDEX."""
26710 i = self.tk.call(self._w, 'index', index)
26720 if i == 'none': return None
26730 return getint(i)
26740 def invoke(self, index):
2675n/a """Invoke a menu item identified by INDEX and execute
2676n/a the associated command."""
26770 return self.tk.call(self._w, 'invoke', index)
26780 def post(self, x, y):
2679n/a """Display a menu at position X,Y."""
26800 self.tk.call(self._w, 'post', x, y)
26810 def type(self, index):
2682n/a """Return the type of the menu item at INDEX."""
26830 return self.tk.call(self._w, 'type', index)
26840 def unpost(self):
2685n/a """Unmap a menu."""
26860 self.tk.call(self._w, 'unpost')
26870 def yposition(self, index):
2688n/a """Return the y-position of the topmost pixel of the menu item at INDEX."""
26890 return getint(self.tk.call(
26900 self._w, 'yposition', index))
2691n/a
26920class Menubutton(Widget):
2693n/a """Menubutton widget, obsolete since Tk8.0."""
26940 def __init__(self, master=None, cnf={}, **kw):
26950 Widget.__init__(self, master, 'menubutton', cnf, kw)
2696n/a
26970class Message(Widget):
2698n/a """Message widget to display multiline text. Obsolete since Label does it too."""
26990 def __init__(self, master=None, cnf={}, **kw):
27000 Widget.__init__(self, master, 'message', cnf, kw)
2701n/a
27020class Radiobutton(Widget):
2703n/a """Radiobutton widget which shows only one of several buttons in on-state."""
27040 def __init__(self, master=None, cnf={}, **kw):
2705n/a """Construct a radiobutton widget with the parent MASTER.
2706n/a
2707n/a Valid resource names: activebackground, activeforeground, anchor,
2708n/a background, bd, bg, bitmap, borderwidth, command, cursor,
2709n/a disabledforeground, fg, font, foreground, height,
2710n/a highlightbackground, highlightcolor, highlightthickness, image,
2711n/a indicatoron, justify, padx, pady, relief, selectcolor, selectimage,
2712n/a state, takefocus, text, textvariable, underline, value, variable,
2713n/a width, wraplength."""
27140 Widget.__init__(self, master, 'radiobutton', cnf, kw)
27150 def deselect(self):
2716n/a """Put the button in off-state."""
2717n/a
27180 self.tk.call(self._w, 'deselect')
27190 def flash(self):
2720n/a """Flash the button."""
27210 self.tk.call(self._w, 'flash')
27220 def invoke(self):
2723n/a """Toggle the button and invoke a command if given as resource."""
27240 return self.tk.call(self._w, 'invoke')
27250 def select(self):
2726n/a """Put the button in on-state."""
27270 self.tk.call(self._w, 'select')
2728n/a
27290class Scale(Widget):
2730n/a """Scale widget which can display a numerical scale."""
27310 def __init__(self, master=None, cnf={}, **kw):
2732n/a """Construct a scale widget with the parent MASTER.
2733n/a
2734n/a Valid resource names: activebackground, background, bigincrement, bd,
2735n/a bg, borderwidth, command, cursor, digits, fg, font, foreground, from,
2736n/a highlightbackground, highlightcolor, highlightthickness, label,
2737n/a length, orient, relief, repeatdelay, repeatinterval, resolution,
2738n/a showvalue, sliderlength, sliderrelief, state, takefocus,
2739n/a tickinterval, to, troughcolor, variable, width."""
27400 Widget.__init__(self, master, 'scale', cnf, kw)
27410 def get(self):
2742n/a """Get the current value as integer or float."""
27430 value = self.tk.call(self._w, 'get')
27440 try:
27450 return getint(value)
27460 except ValueError:
27470 return getdouble(value)
27480 def set(self, value):
2749n/a """Set the value to VALUE."""
27500 self.tk.call(self._w, 'set', value)
27510 def coords(self, value=None):
2752n/a """Return a tuple (X,Y) of the point along the centerline of the
2753n/a trough that corresponds to VALUE or the current value if None is
2754n/a given."""
2755n/a
27560 return self._getints(self.tk.call(self._w, 'coords', value))
27570 def identify(self, x, y):
2758n/a """Return where the point X,Y lies. Valid return values are "slider",
2759n/a "though1" and "though2"."""
27600 return self.tk.call(self._w, 'identify', x, y)
2761n/a
27620class Scrollbar(Widget):
2763n/a """Scrollbar widget which displays a slider at a certain position."""
27640 def __init__(self, master=None, cnf={}, **kw):
2765n/a """Construct a scrollbar widget with the parent MASTER.
2766n/a
2767n/a Valid resource names: activebackground, activerelief,
2768n/a background, bd, bg, borderwidth, command, cursor,
2769n/a elementborderwidth, highlightbackground,
2770n/a highlightcolor, highlightthickness, jump, orient,
2771n/a relief, repeatdelay, repeatinterval, takefocus,
2772n/a troughcolor, width."""
27730 Widget.__init__(self, master, 'scrollbar', cnf, kw)
27740 def activate(self, index):
2775n/a """Display the element at INDEX with activebackground and activerelief.
2776n/a INDEX can be "arrow1","slider" or "arrow2"."""
27770 self.tk.call(self._w, 'activate', index)
27780 def delta(self, deltax, deltay):
2779n/a """Return the fractional change of the scrollbar setting if it
2780n/a would be moved by DELTAX or DELTAY pixels."""
27810 return getdouble(
27820 self.tk.call(self._w, 'delta', deltax, deltay))
27830 def fraction(self, x, y):
2784n/a """Return the fractional value which corresponds to a slider
2785n/a position of X,Y."""
27860 return getdouble(self.tk.call(self._w, 'fraction', x, y))
27870 def identify(self, x, y):
2788n/a """Return the element under position X,Y as one of
2789n/a "arrow1","slider","arrow2" or ""."""
27900 return self.tk.call(self._w, 'identify', x, y)
27910 def get(self):
2792n/a """Return the current fractional values (upper and lower end)
2793n/a of the slider position."""
27940 return self._getdoubles(self.tk.call(self._w, 'get'))
27950 def set(self, *args):
2796n/a """Set the fractional values of the slider position (upper and
2797n/a lower ends as value between 0 and 1)."""
27980 self.tk.call((self._w, 'set') + args)
2799n/a
2800n/a
2801n/a
28020class Text(Widget, XView, YView):
2803n/a """Text widget which can display text in various forms."""
28040 def __init__(self, master=None, cnf={}, **kw):
2805n/a """Construct a text widget with the parent MASTER.
2806n/a
2807n/a STANDARD OPTIONS
2808n/a
2809n/a background, borderwidth, cursor,
2810n/a exportselection, font, foreground,
2811n/a highlightbackground, highlightcolor,
2812n/a highlightthickness, insertbackground,
2813n/a insertborderwidth, insertofftime,
2814n/a insertontime, insertwidth, padx, pady,
2815n/a relief, selectbackground,
2816n/a selectborderwidth, selectforeground,
2817n/a setgrid, takefocus,
2818n/a xscrollcommand, yscrollcommand,
2819n/a
2820n/a WIDGET-SPECIFIC OPTIONS
2821n/a
2822n/a autoseparators, height, maxundo,
2823n/a spacing1, spacing2, spacing3,
2824n/a state, tabs, undo, width, wrap,
2825n/a
2826n/a """
28270 Widget.__init__(self, master, 'text', cnf, kw)
28280 def bbox(self, *args):
2829n/a """Return a tuple of (x,y,width,height) which gives the bounding
2830n/a box of the visible part of the character at the index in ARGS."""
28310 return self._getints(
28320 self.tk.call((self._w, 'bbox') + args)) or None
28330 def tk_textSelectTo(self, index):
28340 self.tk.call('tk_textSelectTo', self._w, index)
28350 def tk_textBackspace(self):
28360 self.tk.call('tk_textBackspace', self._w)
28370 def tk_textIndexCloser(self, a, b, c):
28380 self.tk.call('tk_textIndexCloser', self._w, a, b, c)
28390 def tk_textResetAnchor(self, index):
28400 self.tk.call('tk_textResetAnchor', self._w, index)
28410 def compare(self, index1, op, index2):
2842n/a """Return whether between index INDEX1 and index INDEX2 the
2843n/a relation OP is satisfied. OP is one of <, <=, ==, >=, >, or !=."""
28440 return self.tk.getboolean(self.tk.call(
28450 self._w, 'compare', index1, op, index2))
28460 def debug(self, boolean=None):
2847n/a """Turn on the internal consistency checks of the B-Tree inside the text
2848n/a widget according to BOOLEAN."""
28490 return self.tk.getboolean(self.tk.call(
28500 self._w, 'debug', boolean))
28510 def delete(self, index1, index2=None):
2852n/a """Delete the characters between INDEX1 and INDEX2 (not included)."""
28530 self.tk.call(self._w, 'delete', index1, index2)
28540 def dlineinfo(self, index):
2855n/a """Return tuple (x,y,width,height,baseline) giving the bounding box
2856n/a and baseline position of the visible part of the line containing
2857n/a the character at INDEX."""
28580 return self._getints(self.tk.call(self._w, 'dlineinfo', index))
28590 def dump(self, index1, index2=None, command=None, **kw):
2860n/a """Return the contents of the widget between index1 and index2.
2861n/a
2862n/a The type of contents returned in filtered based on the keyword
2863n/a parameters; if 'all', 'image', 'mark', 'tag', 'text', or 'window' are
2864n/a given and true, then the corresponding items are returned. The result
2865n/a is a list of triples of the form (key, value, index). If none of the
2866n/a keywords are true then 'all' is used by default.
2867n/a
2868n/a If the 'command' argument is given, it is called once for each element
2869n/a of the list of triples, with the values of each triple serving as the
2870n/a arguments to the function. In this case the list is not returned."""
28710 args = []
28720 func_name = None
28730 result = None
28740 if not command:
2875n/a # Never call the dump command without the -command flag, since the
2876n/a # output could involve Tcl quoting and would be a pain to parse
2877n/a # right. Instead just set the command to build a list of triples
2878n/a # as if we had done the parsing.
28790 result = []
28800 def append_triple(key, value, index, result=result):
28810 result.append((key, value, index))
28820 command = append_triple
28830 try:
28840 if not isinstance(command, str):
28850 func_name = command = self._register(command)
28860 args += ["-command", command]
28870 for key in kw:
28880 if kw[key]: args.append("-" + key)
28890 args.append(index1)
28900 if index2:
28910 args.append(index2)
28920 self.tk.call(self._w, "dump", *args)
28930 return result
2894n/a finally:
28950 if func_name:
28960 self.deletecommand(func_name)
2897n/a
2898n/a ## new in tk8.4
28990 def edit(self, *args):
2900n/a """Internal method
2901n/a
2902n/a This method controls the undo mechanism and
2903n/a the modified flag. The exact behavior of the
2904n/a command depends on the option argument that
2905n/a follows the edit argument. The following forms
2906n/a of the command are currently supported:
2907n/a
2908n/a edit_modified, edit_redo, edit_reset, edit_separator
2909n/a and edit_undo
2910n/a
2911n/a """
29120 return self.tk.call(self._w, 'edit', *args)
2913n/a
29140 def edit_modified(self, arg=None):
2915n/a """Get or Set the modified flag
2916n/a
2917n/a If arg is not specified, returns the modified
2918n/a flag of the widget. The insert, delete, edit undo and
2919n/a edit redo commands or the user can set or clear the
2920n/a modified flag. If boolean is specified, sets the
2921n/a modified flag of the widget to arg.
2922n/a """
29230 return self.edit("modified", arg)
2924n/a
29250 def edit_redo(self):
2926n/a """Redo the last undone edit
2927n/a
2928n/a When the undo option is true, reapplies the last
2929n/a undone edits provided no other edits were done since
2930n/a then. Generates an error when the redo stack is empty.
2931n/a Does nothing when the undo option is false.
2932n/a """
29330 return self.edit("redo")
2934n/a
29350 def edit_reset(self):
2936n/a """Clears the undo and redo stacks
2937n/a """
29380 return self.edit("reset")
2939n/a
29400 def edit_separator(self):
2941n/a """Inserts a separator (boundary) on the undo stack.
2942n/a
2943n/a Does nothing when the undo option is false
2944n/a """
29450 return self.edit("separator")
2946n/a
29470 def edit_undo(self):
2948n/a """Undoes the last edit action
2949n/a
2950n/a If the undo option is true. An edit action is defined
2951n/a as all the insert and delete commands that are recorded
2952n/a on the undo stack in between two separators. Generates
2953n/a an error when the undo stack is empty. Does nothing
2954n/a when the undo option is false
2955n/a """
29560 return self.edit("undo")
2957n/a
29580 def get(self, index1, index2=None):
2959n/a """Return the text from INDEX1 to INDEX2 (not included)."""
29600 return self.tk.call(self._w, 'get', index1, index2)
2961n/a # (Image commands are new in 8.0)
29620 def image_cget(self, index, option):
2963n/a """Return the value of OPTION of an embedded image at INDEX."""
29640 if option[:1] != "-":
29650 option = "-" + option
29660 if option[-1:] == "_":
29670 option = option[:-1]
29680 return self.tk.call(self._w, "image", "cget", index, option)
29690 def image_configure(self, index, cnf=None, **kw):
2970n/a """Configure an embedded image at INDEX."""
29710 return self._configure(('image', 'configure', index), cnf, kw)
29720 def image_create(self, index, cnf={}, **kw):
2973n/a """Create an embedded image at INDEX."""
29740 return self.tk.call(
29750 self._w, "image", "create", index,
29760 *self._options(cnf, kw))
29770 def image_names(self):
2978n/a """Return all names of embedded images in this widget."""
29790 return self.tk.call(self._w, "image", "names")
29800 def index(self, index):
2981n/a """Return the index in the form line.char for INDEX."""
29820 return str(self.tk.call(self._w, 'index', index))
29830 def insert(self, index, chars, *args):
2984n/a """Insert CHARS before the characters at INDEX. An additional
2985n/a tag can be given in ARGS. Additional CHARS and tags can follow in ARGS."""
29860 self.tk.call((self._w, 'insert', index, chars) + args)
29870 def mark_gravity(self, markName, direction=None):
2988n/a """Change the gravity of a mark MARKNAME to DIRECTION (LEFT or RIGHT).
2989n/a Return the current value if None is given for DIRECTION."""
29900 return self.tk.call(
29910 (self._w, 'mark', 'gravity', markName, direction))
29920 def mark_names(self):
2993n/a """Return all mark names."""
29940 return self.tk.splitlist(self.tk.call(
29950 self._w, 'mark', 'names'))
29960 def mark_set(self, markName, index):
2997n/a """Set mark MARKNAME before the character at INDEX."""
29980 self.tk.call(self._w, 'mark', 'set', markName, index)
29990 def mark_unset(self, *markNames):
3000n/a """Delete all marks in MARKNAMES."""
30010 self.tk.call((self._w, 'mark', 'unset') + markNames)
30020 def mark_next(self, index):
3003n/a """Return the name of the next mark after INDEX."""
30040 return self.tk.call(self._w, 'mark', 'next', index) or None
30050 def mark_previous(self, index):
3006n/a """Return the name of the previous mark before INDEX."""
30070 return self.tk.call(self._w, 'mark', 'previous', index) or None
30080 def scan_mark(self, x, y):
3009n/a """Remember the current X, Y coordinates."""
30100 self.tk.call(self._w, 'scan', 'mark', x, y)
30110 def scan_dragto(self, x, y):
3012n/a """Adjust the view of the text to 10 times the
3013n/a difference between X and Y and the coordinates given in
3014n/a scan_mark."""
30150 self.tk.call(self._w, 'scan', 'dragto', x, y)
30160 def search(self, pattern, index, stopindex=None,
30170 forwards=None, backwards=None, exact=None,
30180 regexp=None, nocase=None, count=None, elide=None):
3019n/a """Search PATTERN beginning from INDEX until STOPINDEX.
3020n/a Return the index of the first character of a match or an
3021n/a empty string."""
30220 args = [self._w, 'search']
30230 if forwards: args.append('-forwards')
30240 if backwards: args.append('-backwards')
30250 if exact: args.append('-exact')
30260 if regexp: args.append('-regexp')
30270 if nocase: args.append('-nocase')
30280 if elide: args.append('-elide')
30290 if count: args.append('-count'); args.append(count)
30300 if pattern and pattern[0] == '-': args.append('--')
30310 args.append(pattern)
30320 args.append(index)
30330 if stopindex: args.append(stopindex)
30340 return str(self.tk.call(tuple(args)))
30350 def see(self, index):
3036n/a """Scroll such that the character at INDEX is visible."""
30370 self.tk.call(self._w, 'see', index)
30380 def tag_add(self, tagName, index1, *args):
3039n/a """Add tag TAGNAME to all characters between INDEX1 and index2 in ARGS.
3040n/a Additional pairs of indices may follow in ARGS."""
30410 self.tk.call(
30420 (self._w, 'tag', 'add', tagName, index1) + args)
30430 def tag_unbind(self, tagName, sequence, funcid=None):
3044n/a """Unbind for all characters with TAGNAME for event SEQUENCE the
3045n/a function identified with FUNCID."""
30460 self.tk.call(self._w, 'tag', 'bind', tagName, sequence, '')
30470 if funcid:
30480 self.deletecommand(funcid)
30490 def tag_bind(self, tagName, sequence, func, add=None):
3050n/a """Bind to all characters with TAGNAME at event SEQUENCE a call to function FUNC.
3051n/a
3052n/a An additional boolean parameter ADD specifies whether FUNC will be
3053n/a called additionally to the other bound function or whether it will
3054n/a replace the previous function. See bind for the return value."""
30550 return self._bind((self._w, 'tag', 'bind', tagName),
30560 sequence, func, add)
30570 def tag_cget(self, tagName, option):
3058n/a """Return the value of OPTION for tag TAGNAME."""
30590 if option[:1] != '-':
30600 option = '-' + option
30610 if option[-1:] == '_':
30620 option = option[:-1]
30630 return self.tk.call(self._w, 'tag', 'cget', tagName, option)
30640 def tag_configure(self, tagName, cnf=None, **kw):
3065n/a """Configure a tag TAGNAME."""
30660 return self._configure(('tag', 'configure', tagName), cnf, kw)
30670 tag_config = tag_configure
30680 def tag_delete(self, *tagNames):
3069n/a """Delete all tags in TAGNAMES."""
30700 self.tk.call((self._w, 'tag', 'delete') + tagNames)
30710 def tag_lower(self, tagName, belowThis=None):
3072n/a """Change the priority of tag TAGNAME such that it is lower
3073n/a than the priority of BELOWTHIS."""
30740 self.tk.call(self._w, 'tag', 'lower', tagName, belowThis)
30750 def tag_names(self, index=None):
3076n/a """Return a list of all tag names."""
30770 return self.tk.splitlist(
30780 self.tk.call(self._w, 'tag', 'names', index))
30790 def tag_nextrange(self, tagName, index1, index2=None):
3080n/a """Return a list of start and end index for the first sequence of
3081n/a characters between INDEX1 and INDEX2 which all have tag TAGNAME.
3082n/a The text is searched forward from INDEX1."""
30830 return self.tk.splitlist(self.tk.call(
30840 self._w, 'tag', 'nextrange', tagName, index1, index2))
30850 def tag_prevrange(self, tagName, index1, index2=None):
3086n/a """Return a list of start and end index for the first sequence of
3087n/a characters between INDEX1 and INDEX2 which all have tag TAGNAME.
3088n/a The text is searched backwards from INDEX1."""
30890 return self.tk.splitlist(self.tk.call(
30900 self._w, 'tag', 'prevrange', tagName, index1, index2))
30910 def tag_raise(self, tagName, aboveThis=None):
3092n/a """Change the priority of tag TAGNAME such that it is higher
3093n/a than the priority of ABOVETHIS."""
30940 self.tk.call(
30950 self._w, 'tag', 'raise', tagName, aboveThis)
30960 def tag_ranges(self, tagName):
3097n/a """Return a list of ranges of text which have tag TAGNAME."""
30980 return self.tk.splitlist(self.tk.call(
30990 self._w, 'tag', 'ranges', tagName))
31000 def tag_remove(self, tagName, index1, index2=None):
3101n/a """Remove tag TAGNAME from all characters between INDEX1 and INDEX2."""
31020 self.tk.call(
31030 self._w, 'tag', 'remove', tagName, index1, index2)
31040 def window_cget(self, index, option):
3105n/a """Return the value of OPTION of an embedded window at INDEX."""
31060 if option[:1] != '-':
31070 option = '-' + option
31080 if option[-1:] == '_':
31090 option = option[:-1]
31100 return self.tk.call(self._w, 'window', 'cget', index, option)
31110 def window_configure(self, index, cnf=None, **kw):
3112n/a """Configure an embedded window at INDEX."""
31130 return self._configure(('window', 'configure', index), cnf, kw)
31140 window_config = window_configure
31150 def window_create(self, index, cnf={}, **kw):
3116n/a """Create a window at INDEX."""
31170 self.tk.call(
31180 (self._w, 'window', 'create', index)
31190 + self._options(cnf, kw))
31200 def window_names(self):
3121n/a """Return all names of embedded windows in this widget."""
31220 return self.tk.splitlist(
31230 self.tk.call(self._w, 'window', 'names'))
31240 def yview_pickplace(self, *what):
3125n/a """Obsolete function, use see."""
31260 self.tk.call((self._w, 'yview', '-pickplace') + what)
3127n/a
3128n/a
31290class _setit:
3130n/a """Internal class. It wraps the command in the widget OptionMenu."""
31310 def __init__(self, var, value, callback=None):
31320 self.__value = value
31330 self.__var = var
31340 self.__callback = callback
31350 def __call__(self, *args):
31360 self.__var.set(self.__value)
31370 if self.__callback:
31380 self.__callback(self.__value, *args)
3139n/a
31400class OptionMenu(Menubutton):
3141n/a """OptionMenu which allows the user to select a value from a menu."""
31420 def __init__(self, master, variable, value, *values, **kwargs):
3143n/a """Construct an optionmenu widget with the parent MASTER, with
3144n/a the resource textvariable set to VARIABLE, the initially selected
3145n/a value VALUE, the other menu values VALUES and an additional
3146n/a keyword argument command."""
31470 kw = {"borderwidth": 2, "textvariable": variable,
31480 "indicatoron": 1, "relief": RAISED, "anchor": "c",
31490 "highlightthickness": 2}
31500 Widget.__init__(self, master, "menubutton", kw)
31510 self.widgetName = 'tk_optionMenu'
31520 menu = self.__menu = Menu(self, name="menu", tearoff=0)
31530 self.menuname = menu._w
3154n/a # 'command' is the only supported keyword
31550 callback = kwargs.get('command')
31560 if 'command' in kwargs:
31570 del kwargs['command']
31580 if kwargs:
31590 raise TclError, 'unknown option -'+kwargs.keys()[0]
31600 menu.add_command(label=value,
31610 command=_setit(variable, value, callback))
31620 for v in values:
31630 menu.add_command(label=v,
31640 command=_setit(variable, v, callback))
31650 self["menu"] = menu
3166n/a
31670 def __getitem__(self, name):
31680 if name == 'menu':
31690 return self.__menu
31700 return Widget.__getitem__(self, name)
3171n/a
31720 def destroy(self):
3173n/a """Destroy this widget and the associated menu."""
31740 Menubutton.destroy(self)
31750 self.__menu = None
3176n/a
31770class Image:
3178n/a """Base class for images."""
31790 _last_id = 0
31800 def __init__(self, imgtype, name=None, cnf={}, master=None, **kw):
31810 self.name = None
31820 if not master:
31830 master = _default_root
31840 if not master:
31850 raise RuntimeError, 'Too early to create image'
31860 self.tk = master.tk
31870 if not name:
31880 Image._last_id += 1
31890 name = "pyimage%r" % (Image._last_id,) # tk itself would use image<x>
3190n/a # The following is needed for systems where id(x)
3191n/a # can return a negative number, such as Linux/m68k:
31920 if name[0] == '-': name = '_' + name[1:]
31930 if kw and cnf: cnf = _cnfmerge((cnf, kw))
31940 elif kw: cnf = kw
31950 options = ()
31960 for k, v in cnf.items():
31970 if hasattr(v, '__call__'):
31980 v = self._register(v)
31990 options = options + ('-'+k, v)
32000 self.tk.call(('image', 'create', imgtype, name,) + options)
32010 self.name = name
32020 def __str__(self): return self.name
32030 def __del__(self):
32040 if self.name:
32050 try:
32060 self.tk.call('image', 'delete', self.name)
32070 except TclError:
3208n/a # May happen if the root was destroyed
32090 pass
32100 def __setitem__(self, key, value):
32110 self.tk.call(self.name, 'configure', '-'+key, value)
32120 def __getitem__(self, key):
32130 return self.tk.call(self.name, 'configure', '-'+key)
32140 def configure(self, **kw):
3215n/a """Configure the image."""
32160 res = ()
32170 for k, v in _cnfmerge(kw).items():
32180 if v is not None:
32190 if k[-1] == '_': k = k[:-1]
32200 if hasattr(v, '__call__'):
32210 v = self._register(v)
32220 res = res + ('-'+k, v)
32230 self.tk.call((self.name, 'config') + res)
32240 config = configure
32250 def height(self):
3226n/a """Return the height of the image."""
32270 return getint(
32280 self.tk.call('image', 'height', self.name))
32290 def type(self):
3230n/a """Return the type of the imgage, e.g. "photo" or "bitmap"."""
32310 return self.tk.call('image', 'type', self.name)
32320 def width(self):
3233n/a """Return the width of the image."""
32340 return getint(
32350 self.tk.call('image', 'width', self.name))
3236n/a
32370class PhotoImage(Image):
3238n/a """Widget which can display colored images in GIF, PPM/PGM format."""
32390 def __init__(self, name=None, cnf={}, master=None, **kw):
3240n/a """Create an image with NAME.
3241n/a
3242n/a Valid resource names: data, format, file, gamma, height, palette,
3243n/a width."""
32440 Image.__init__(self, 'photo', name, cnf, master, **kw)
32450 def blank(self):
3246n/a """Display a transparent image."""
32470 self.tk.call(self.name, 'blank')
32480 def cget(self, option):
3249n/a """Return the value of OPTION."""
32500 return self.tk.call(self.name, 'cget', '-' + option)
3251n/a # XXX config
32520 def __getitem__(self, key):
32530 return self.tk.call(self.name, 'cget', '-' + key)
3254n/a # XXX copy -from, -to, ...?
32550 def copy(self):
3256n/a """Return a new PhotoImage with the same image as this widget."""
32570 destImage = PhotoImage()
32580 self.tk.call(destImage, 'copy', self.name)
32590 return destImage
32600 def zoom(self,x,y=''):
3261n/a """Return a new PhotoImage with the same image as this widget
3262n/a but zoom it with X and Y."""
32630 destImage = PhotoImage()
32640 if y=='': y=x
32650 self.tk.call(destImage, 'copy', self.name, '-zoom',x,y)
32660 return destImage
32670 def subsample(self,x,y=''):
3268n/a """Return a new PhotoImage based on the same image as this widget
3269n/a but use only every Xth or Yth pixel."""
32700 destImage = PhotoImage()
32710 if y=='': y=x
32720 self.tk.call(destImage, 'copy', self.name, '-subsample',x,y)
32730 return destImage
32740 def get(self, x, y):
3275n/a """Return the color (red, green, blue) of the pixel at X,Y."""
32760 return self.tk.call(self.name, 'get', x, y)
32770 def put(self, data, to=None):
3278n/a """Put row formatted colors to image starting from
3279n/a position TO, e.g. image.put("{red green} {blue yellow}", to=(4,6))"""
32800 args = (self.name, 'put', data)
32810 if to:
32820 if to[0] == '-to':
32830 to = to[1:]
32840 args = args + ('-to',) + tuple(to)
32850 self.tk.call(args)
3286n/a # XXX read
32870 def write(self, filename, format=None, from_coords=None):
3288n/a """Write image to file FILENAME in FORMAT starting from
3289n/a position FROM_COORDS."""
32900 args = (self.name, 'write', filename)
32910 if format:
32920 args = args + ('-format', format)
32930 if from_coords:
32940 args = args + ('-from',) + tuple(from_coords)
32950 self.tk.call(args)
3296n/a
32970class BitmapImage(Image):
3298n/a """Widget which can display a bitmap."""
32990 def __init__(self, name=None, cnf={}, master=None, **kw):
3300n/a """Create a bitmap with NAME.
3301n/a
3302n/a Valid resource names: background, data, file, foreground, maskdata, maskfile."""
33030 Image.__init__(self, 'bitmap', name, cnf, master, **kw)
3304n/a
33050def image_names(): return _default_root.tk.call('image', 'names')
33060def image_types(): return _default_root.tk.call('image', 'types')
3307n/a
3308n/a
33090class Spinbox(Widget, XView):
3310n/a """spinbox widget."""
33110 def __init__(self, master=None, cnf={}, **kw):
3312n/a """Construct a spinbox widget with the parent MASTER.
3313n/a
3314n/a STANDARD OPTIONS
3315n/a
3316n/a activebackground, background, borderwidth,
3317n/a cursor, exportselection, font, foreground,
3318n/a highlightbackground, highlightcolor,
3319n/a highlightthickness, insertbackground,
3320n/a insertborderwidth, insertofftime,
3321n/a insertontime, insertwidth, justify, relief,
3322n/a repeatdelay, repeatinterval,
3323n/a selectbackground, selectborderwidth
3324n/a selectforeground, takefocus, textvariable
3325n/a xscrollcommand.
3326n/a
3327n/a WIDGET-SPECIFIC OPTIONS
3328n/a
3329n/a buttonbackground, buttoncursor,
3330n/a buttondownrelief, buttonuprelief,
3331n/a command, disabledbackground,
3332n/a disabledforeground, format, from,
3333n/a invalidcommand, increment,
3334n/a readonlybackground, state, to,
3335n/a validate, validatecommand values,
3336n/a width, wrap,
3337n/a """
33380 Widget.__init__(self, master, 'spinbox', cnf, kw)
3339n/a
33400 def bbox(self, index):
3341n/a """Return a tuple of X1,Y1,X2,Y2 coordinates for a
3342n/a rectangle which encloses the character given by index.
3343n/a
3344n/a The first two elements of the list give the x and y
3345n/a coordinates of the upper-left corner of the screen
3346n/a area covered by the character (in pixels relative
3347n/a to the widget) and the last two elements give the
3348n/a width and height of the character, in pixels. The
3349n/a bounding box may refer to a region outside the
3350n/a visible area of the window.
3351n/a """
33520 return self.tk.call(self._w, 'bbox', index)
3353n/a
33540 def delete(self, first, last=None):
3355n/a """Delete one or more elements of the spinbox.
3356n/a
3357n/a First is the index of the first character to delete,
3358n/a and last is the index of the character just after
3359n/a the last one to delete. If last isn't specified it
3360n/a defaults to first+1, i.e. a single character is
3361n/a deleted. This command returns an empty string.
3362n/a """
33630 return self.tk.call(self._w, 'delete', first, last)
3364n/a
33650 def get(self):
3366n/a """Returns the spinbox's string"""
33670 return self.tk.call(self._w, 'get')
3368n/a
33690 def icursor(self, index):
3370n/a """Alter the position of the insertion cursor.
3371n/a
3372n/a The insertion cursor will be displayed just before
3373n/a the character given by index. Returns an empty string
3374n/a """
33750 return self.tk.call(self._w, 'icursor', index)
3376n/a
33770 def identify(self, x, y):
3378n/a """Returns the name of the widget at position x, y
3379n/a
3380n/a Return value is one of: none, buttondown, buttonup, entry
3381n/a """
33820 return self.tk.call(self._w, 'identify', x, y)
3383n/a
33840 def index(self, index):
3385n/a """Returns the numerical index corresponding to index
3386n/a """
33870 return self.tk.call(self._w, 'index', index)
3388n/a
33890 def insert(self, index, s):
3390n/a """Insert string s at index
3391n/a
3392n/a Returns an empty string.
3393n/a """
33940 return self.tk.call(self._w, 'insert', index, s)
3395n/a
33960 def invoke(self, element):
3397n/a """Causes the specified element to be invoked
3398n/a
3399n/a The element could be buttondown or buttonup
3400n/a triggering the action associated with it.
3401n/a """
34020 return self.tk.call(self._w, 'invoke', element)
3403n/a
34040 def scan(self, *args):
3405n/a """Internal function."""
34060 return self._getints(
34070 self.tk.call((self._w, 'scan') + args)) or ()
3408n/a
34090 def scan_mark(self, x):
3410n/a """Records x and the current view in the spinbox window;
3411n/a
3412n/a used in conjunction with later scan dragto commands.
3413n/a Typically this command is associated with a mouse button
3414n/a press in the widget. It returns an empty string.
3415n/a """
34160 return self.scan("mark", x)
3417n/a
34180 def scan_dragto(self, x):
3419n/a """Compute the difference between the given x argument
3420n/a and the x argument to the last scan mark command
3421n/a
3422n/a It then adjusts the view left or right by 10 times the
3423n/a difference in x-coordinates. This command is typically
3424n/a associated with mouse motion events in the widget, to
3425n/a produce the effect of dragging the spinbox at high speed
3426n/a through the window. The return value is an empty string.
3427n/a """
34280 return self.scan("dragto", x)
3429n/a
34300 def selection(self, *args):
3431n/a """Internal function."""
34320 return self._getints(
34330 self.tk.call((self._w, 'selection') + args)) or ()
3434n/a
34350 def selection_adjust(self, index):
3436n/a """Locate the end of the selection nearest to the character
3437n/a given by index,
3438n/a
3439n/a Then adjust that end of the selection to be at index
3440n/a (i.e including but not going beyond index). The other
3441n/a end of the selection is made the anchor point for future
3442n/a select to commands. If the selection isn't currently in
3443n/a the spinbox, then a new selection is created to include
3444n/a the characters between index and the most recent selection
3445n/a anchor point, inclusive. Returns an empty string.
3446n/a """
34470 return self.selection("adjust", index)
3448n/a
34490 def selection_clear(self):
3450n/a """Clear the selection
3451n/a
3452n/a If the selection isn't in this widget then the
3453n/a command has no effect. Returns an empty string.
3454n/a """
34550 return self.selection("clear")
3456n/a
34570 def selection_element(self, element=None):
3458n/a """Sets or gets the currently selected element.
3459n/a
3460n/a If a spinbutton element is specified, it will be
3461n/a displayed depressed
3462n/a """
34630 return self.selection("element", element)
3464n/a
3465n/a###########################################################################
3466n/a
34670class LabelFrame(Widget):
3468n/a """labelframe widget."""
34690 def __init__(self, master=None, cnf={}, **kw):
3470n/a """Construct a labelframe widget with the parent MASTER.
3471n/a
3472n/a STANDARD OPTIONS
3473n/a
3474n/a borderwidth, cursor, font, foreground,
3475n/a highlightbackground, highlightcolor,
3476n/a highlightthickness, padx, pady, relief,
3477n/a takefocus, text
3478n/a
3479n/a WIDGET-SPECIFIC OPTIONS
3480n/a
3481n/a background, class, colormap, container,
3482n/a height, labelanchor, labelwidget,
3483n/a visual, width
3484n/a """
34850 Widget.__init__(self, master, 'labelframe', cnf, kw)
3486n/a
3487n/a########################################################################
3488n/a
34890class PanedWindow(Widget):
3490n/a """panedwindow widget."""
34910 def __init__(self, master=None, cnf={}, **kw):
3492n/a """Construct a panedwindow widget with the parent MASTER.
3493n/a
3494n/a STANDARD OPTIONS
3495n/a
3496n/a background, borderwidth, cursor, height,
3497n/a orient, relief, width
3498n/a
3499n/a WIDGET-SPECIFIC OPTIONS
3500n/a
3501n/a handlepad, handlesize, opaqueresize,
3502n/a sashcursor, sashpad, sashrelief,
3503n/a sashwidth, showhandle,
3504n/a """
35050 Widget.__init__(self, master, 'panedwindow', cnf, kw)
3506n/a
35070 def add(self, child, **kw):
3508n/a """Add a child widget to the panedwindow in a new pane.
3509n/a
3510n/a The child argument is the name of the child widget
3511n/a followed by pairs of arguments that specify how to
3512n/a manage the windows. The possible options and values
3513n/a are the ones accepted by the paneconfigure method.
3514n/a """
35150 self.tk.call((self._w, 'add', child) + self._options(kw))
3516n/a
35170 def remove(self, child):
3518n/a """Remove the pane containing child from the panedwindow
3519n/a
3520n/a All geometry management options for child will be forgotten.
3521n/a """
35220 self.tk.call(self._w, 'forget', child)
35230 forget=remove
3524n/a
35250 def identify(self, x, y):
3526n/a """Identify the panedwindow component at point x, y
3527n/a
3528n/a If the point is over a sash or a sash handle, the result
3529n/a is a two element list containing the index of the sash or
3530n/a handle, and a word indicating whether it is over a sash
3531n/a or a handle, such as {0 sash} or {2 handle}. If the point
3532n/a is over any other part of the panedwindow, the result is
3533n/a an empty list.
3534n/a """
35350 return self.tk.call(self._w, 'identify', x, y)
3536n/a
35370 def proxy(self, *args):
3538n/a """Internal function."""
35390 return self._getints(
35400 self.tk.call((self._w, 'proxy') + args)) or ()
3541n/a
35420 def proxy_coord(self):
3543n/a """Return the x and y pair of the most recent proxy location
3544n/a """
35450 return self.proxy("coord")
3546n/a
35470 def proxy_forget(self):
3548n/a """Remove the proxy from the display.
3549n/a """
35500 return self.proxy("forget")
3551n/a
35520 def proxy_place(self, x, y):
3553n/a """Place the proxy at the given x and y coordinates.
3554n/a """
35550 return self.proxy("place", x, y)
3556n/a
35570 def sash(self, *args):
3558n/a """Internal function."""
35590 return self._getints(
35600 self.tk.call((self._w, 'sash') + args)) or ()
3561n/a
35620 def sash_coord(self, index):
3563n/a """Return the current x and y pair for the sash given by index.
3564n/a
3565n/a Index must be an integer between 0 and 1 less than the
3566n/a number of panes in the panedwindow. The coordinates given are
3567n/a those of the top left corner of the region containing the sash.
3568n/a pathName sash dragto index x y This command computes the
3569n/a difference between the given coordinates and the coordinates
3570n/a given to the last sash coord command for the given sash. It then
3571n/a moves that sash the computed difference. The return value is the
3572n/a empty string.
3573n/a """
35740 return self.sash("coord", index)
3575n/a
35760 def sash_mark(self, index):
3577n/a """Records x and y for the sash given by index;
3578n/a
3579n/a Used in conjunction with later dragto commands to move the sash.
3580n/a """
35810 return self.sash("mark", index)
3582n/a
35830 def sash_place(self, index, x, y):
3584n/a """Place the sash given by index at the given coordinates
3585n/a """
35860 return self.sash("place", index, x, y)
3587n/a
35880 def panecget(self, child, option):
3589n/a """Query a management option for window.
3590n/a
3591n/a Option may be any value allowed by the paneconfigure subcommand
3592n/a """
35930 return self.tk.call(
35940 (self._w, 'panecget') + (child, '-'+option))
3595n/a
35960 def paneconfigure(self, tagOrId, cnf=None, **kw):
3597n/a """Query or modify the management options for window.
3598n/a
3599n/a If no option is specified, returns a list describing all
3600n/a of the available options for pathName. If option is
3601n/a specified with no value, then the command returns a list
3602n/a describing the one named option (this list will be identical
3603n/a to the corresponding sublist of the value returned if no
3604n/a option is specified). If one or more option-value pairs are
3605n/a specified, then the command modifies the given widget
3606n/a option(s) to have the given value(s); in this case the
3607n/a command returns an empty string. The following options
3608n/a are supported:
3609n/a
3610n/a after window
3611n/a Insert the window after the window specified. window
3612n/a should be the name of a window already managed by pathName.
3613n/a before window
3614n/a Insert the window before the window specified. window
3615n/a should be the name of a window already managed by pathName.
3616n/a height size
3617n/a Specify a height for the window. The height will be the
3618n/a outer dimension of the window including its border, if
3619n/a any. If size is an empty string, or if -height is not
3620n/a specified, then the height requested internally by the
3621n/a window will be used initially; the height may later be
3622n/a adjusted by the movement of sashes in the panedwindow.
3623n/a Size may be any value accepted by Tk_GetPixels.
3624n/a minsize n
3625n/a Specifies that the size of the window cannot be made
3626n/a less than n. This constraint only affects the size of
3627n/a the widget in the paned dimension -- the x dimension
3628n/a for horizontal panedwindows, the y dimension for
3629n/a vertical panedwindows. May be any value accepted by
3630n/a Tk_GetPixels.
3631n/a padx n
3632n/a Specifies a non-negative value indicating how much
3633n/a extra space to leave on each side of the window in
3634n/a the X-direction. The value may have any of the forms
3635n/a accepted by Tk_GetPixels.
3636n/a pady n
3637n/a Specifies a non-negative value indicating how much
3638n/a extra space to leave on each side of the window in
3639n/a the Y-direction. The value may have any of the forms
3640n/a accepted by Tk_GetPixels.
3641n/a sticky style
3642n/a If a window's pane is larger than the requested
3643n/a dimensions of the window, this option may be used
3644n/a to position (or stretch) the window within its pane.
3645n/a Style is a string that contains zero or more of the
3646n/a characters n, s, e or w. The string can optionally
3647n/a contains spaces or commas, but they are ignored. Each
3648n/a letter refers to a side (north, south, east, or west)
3649n/a that the window will "stick" to. If both n and s
3650n/a (or e and w) are specified, the window will be
3651n/a stretched to fill the entire height (or width) of
3652n/a its cavity.
3653n/a width size
3654n/a Specify a width for the window. The width will be
3655n/a the outer dimension of the window including its
3656n/a border, if any. If size is an empty string, or
3657n/a if -width is not specified, then the width requested
3658n/a internally by the window will be used initially; the
3659n/a width may later be adjusted by the movement of sashes
3660n/a in the panedwindow. Size may be any value accepted by
3661n/a Tk_GetPixels.
3662n/a
3663n/a """
36640 if cnf is None and not kw:
36650 cnf = {}
36660 for x in self.tk.split(
36670 self.tk.call(self._w,
36680 'paneconfigure', tagOrId)):
36690 cnf[x[0][1:]] = (x[0][1:],) + x[1:]
36700 return cnf
36710 if type(cnf) == StringType and not kw:
36720 x = self.tk.split(self.tk.call(
36730 self._w, 'paneconfigure', tagOrId, '-'+cnf))
36740 return (x[0][1:],) + x[1:]
36750 self.tk.call((self._w, 'paneconfigure', tagOrId) +
36760 self._options(cnf, kw))
36770 paneconfig = paneconfigure
3678n/a
36790 def panes(self):
3680n/a """Returns an ordered list of the child panes."""
36810 return self.tk.call(self._w, 'panes')
3682n/a
3683n/a######################################################################
3684n/a# Extensions:
3685n/a
36860class Studbutton(Button):
36870 def __init__(self, master=None, cnf={}, **kw):
36880 Widget.__init__(self, master, 'studbutton', cnf, kw)
36890 self.bind('<Any-Enter>', self.tkButtonEnter)
36900 self.bind('<Any-Leave>', self.tkButtonLeave)
36910 self.bind('<1>', self.tkButtonDown)
36920 self.bind('<ButtonRelease-1>', self.tkButtonUp)
3693n/a
36940class Tributton(Button):
36950 def __init__(self, master=None, cnf={}, **kw):
36960 Widget.__init__(self, master, 'tributton', cnf, kw)
36970 self.bind('<Any-Enter>', self.tkButtonEnter)
36980 self.bind('<Any-Leave>', self.tkButtonLeave)
36990 self.bind('<1>', self.tkButtonDown)
37000 self.bind('<ButtonRelease-1>', self.tkButtonUp)
37010 self['fg'] = self['bg']
37020 self['activebackground'] = self['bg']
3703n/a
3704n/a######################################################################
3705n/a# Test:
3706n/a
37070def _test():
37080 root = Tk()
37090 text = "This is Tcl/Tk version %s" % TclVersion
37100 if TclVersion >= 8.1:
37110 try:
37120 text = text + unicode("\nThis should be a cedilla: \347",
37130 "iso-8859-1")
37140 except NameError:
37150 pass # no unicode support
37160 label = Label(root, text=text)
37170 label.pack()
37180 test = Button(root, text="Click me!",
37190 command=lambda root=root: root.test.configure(
37200 text="[%s]" % root.test['text']))
37210 test.pack()
37220 root.test = test
37230 quit = Button(root, text="QUIT", command=root.destroy)
37240 quit.pack()
3725n/a # The following three commands are needed so the window pops
3726n/a # up on top on Windows...
37270 root.iconify()
37280 root.update()
37290 root.deiconify()
37300 root.mainloop()
3731n/a
37320if __name__ == '__main__':
37330 _test()