ยปCore Development>Code coverage>Lib/tkinter/__init__.py

Python code coverage for Lib/tkinter/__init__.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 tkinter.constants 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()
31n/a"""
32n/a
33n/aimport enum
34n/aimport sys
35n/a
36n/aimport _tkinter # If this fails your Python may not be configured for Tk
37n/aTclError = _tkinter.TclError
38n/afrom tkinter.constants import *
39n/aimport re
40n/a
41n/a
42n/awantobjects = 1
43n/a
44n/aTkVersion = float(_tkinter.TK_VERSION)
45n/aTclVersion = float(_tkinter.TCL_VERSION)
46n/a
47n/aREADABLE = _tkinter.READABLE
48n/aWRITABLE = _tkinter.WRITABLE
49n/aEXCEPTION = _tkinter.EXCEPTION
50n/a
51n/a
52n/a_magic_re = re.compile(r'([\\{}])')
53n/a_space_re = re.compile(r'([\s])', re.ASCII)
54n/a
55n/adef _join(value):
56n/a """Internal function."""
57n/a return ' '.join(map(_stringify, value))
58n/a
59n/adef _stringify(value):
60n/a """Internal function."""
61n/a if isinstance(value, (list, tuple)):
62n/a if len(value) == 1:
63n/a value = _stringify(value[0])
64n/a if value[0] == '{':
65n/a value = '{%s}' % value
66n/a else:
67n/a value = '{%s}' % _join(value)
68n/a else:
69n/a value = str(value)
70n/a if not value:
71n/a value = '{}'
72n/a elif _magic_re.search(value):
73n/a # add '\' before special characters and spaces
74n/a value = _magic_re.sub(r'\\\1', value)
75n/a value = _space_re.sub(r'\\\1', value)
76n/a elif value[0] == '"' or _space_re.search(value):
77n/a value = '{%s}' % value
78n/a return value
79n/a
80n/adef _flatten(seq):
81n/a """Internal function."""
82n/a res = ()
83n/a for item in seq:
84n/a if isinstance(item, (tuple, list)):
85n/a res = res + _flatten(item)
86n/a elif item is not None:
87n/a res = res + (item,)
88n/a return res
89n/a
90n/atry: _flatten = _tkinter._flatten
91n/aexcept AttributeError: pass
92n/a
93n/adef _cnfmerge(cnfs):
94n/a """Internal function."""
95n/a if isinstance(cnfs, dict):
96n/a return cnfs
97n/a elif isinstance(cnfs, (type(None), str)):
98n/a return cnfs
99n/a else:
100n/a cnf = {}
101n/a for c in _flatten(cnfs):
102n/a try:
103n/a cnf.update(c)
104n/a except (AttributeError, TypeError) as msg:
105n/a print("_cnfmerge: fallback due to:", msg)
106n/a for k, v in c.items():
107n/a cnf[k] = v
108n/a return cnf
109n/a
110n/atry: _cnfmerge = _tkinter._cnfmerge
111n/aexcept AttributeError: pass
112n/a
113n/adef _splitdict(tk, v, cut_minus=True, conv=None):
114n/a """Return a properly formatted dict built from Tcl list pairs.
115n/a
116n/a If cut_minus is True, the supposed '-' prefix will be removed from
117n/a keys. If conv is specified, it is used to convert values.
118n/a
119n/a Tcl list is expected to contain an even number of elements.
120n/a """
121n/a t = tk.splitlist(v)
122n/a if len(t) % 2:
123n/a raise RuntimeError('Tcl list representing a dict is expected '
124n/a 'to contain an even number of elements')
125n/a it = iter(t)
126n/a dict = {}
127n/a for key, value in zip(it, it):
128n/a key = str(key)
129n/a if cut_minus and key[0] == '-':
130n/a key = key[1:]
131n/a if conv:
132n/a value = conv(value)
133n/a dict[key] = value
134n/a return dict
135n/a
136n/a
137n/aclass EventType(str, enum.Enum):
138n/a KeyPress = '2'
139n/a Key = KeyPress,
140n/a KeyRelease = '3'
141n/a ButtonPress = '4'
142n/a Button = ButtonPress,
143n/a ButtonRelease = '5'
144n/a Motion = '6'
145n/a Enter = '7'
146n/a Leave = '8'
147n/a FocusIn = '9'
148n/a FocusOut = '10'
149n/a Keymap = '11' # undocumented
150n/a Expose = '12'
151n/a GraphicsExpose = '13' # undocumented
152n/a NoExpose = '14' # undocumented
153n/a Visibility = '15'
154n/a Create = '16'
155n/a Destroy = '17'
156n/a Unmap = '18'
157n/a Map = '19'
158n/a MapRequest = '20'
159n/a Reparent = '21'
160n/a Configure = '22'
161n/a ConfigureRequest = '23'
162n/a Gravity = '24'
163n/a ResizeRequest = '25'
164n/a Circulate = '26'
165n/a CirculateRequest = '27'
166n/a Property = '28'
167n/a SelectionClear = '29' # undocumented
168n/a SelectionRequest = '30' # undocumented
169n/a Selection = '31' # undocumented
170n/a Colormap = '32'
171n/a ClientMessage = '33' # undocumented
172n/a Mapping = '34' # undocumented
173n/a VirtualEvent = '35', # undocumented
174n/a Activate = '36',
175n/a Deactivate = '37',
176n/a MouseWheel = '38',
177n/a def __str__(self):
178n/a return self.name
179n/a
180n/aclass Event:
181n/a """Container for the properties of an event.
182n/a
183n/a Instances of this type are generated if one of the following events occurs:
184n/a
185n/a KeyPress, KeyRelease - for keyboard events
186n/a ButtonPress, ButtonRelease, Motion, Enter, Leave, MouseWheel - for mouse events
187n/a Visibility, Unmap, Map, Expose, FocusIn, FocusOut, Circulate,
188n/a Colormap, Gravity, Reparent, Property, Destroy, Activate,
189n/a Deactivate - for window events.
190n/a
191n/a If a callback function for one of these events is registered
192n/a using bind, bind_all, bind_class, or tag_bind, the callback is
193n/a called with an Event as first argument. It will have the
194n/a following attributes (in braces are the event types for which
195n/a the attribute is valid):
196n/a
197n/a serial - serial number of event
198n/a num - mouse button pressed (ButtonPress, ButtonRelease)
199n/a focus - whether the window has the focus (Enter, Leave)
200n/a height - height of the exposed window (Configure, Expose)
201n/a width - width of the exposed window (Configure, Expose)
202n/a keycode - keycode of the pressed key (KeyPress, KeyRelease)
203n/a state - state of the event as a number (ButtonPress, ButtonRelease,
204n/a Enter, KeyPress, KeyRelease,
205n/a Leave, Motion)
206n/a state - state as a string (Visibility)
207n/a time - when the event occurred
208n/a x - x-position of the mouse
209n/a y - y-position of the mouse
210n/a x_root - x-position of the mouse on the screen
211n/a (ButtonPress, ButtonRelease, KeyPress, KeyRelease, Motion)
212n/a y_root - y-position of the mouse on the screen
213n/a (ButtonPress, ButtonRelease, KeyPress, KeyRelease, Motion)
214n/a char - pressed character (KeyPress, KeyRelease)
215n/a send_event - see X/Windows documentation
216n/a keysym - keysym of the event as a string (KeyPress, KeyRelease)
217n/a keysym_num - keysym of the event as a number (KeyPress, KeyRelease)
218n/a type - type of the event as a number
219n/a widget - widget in which the event occurred
220n/a delta - delta of wheel movement (MouseWheel)
221n/a """
222n/a def __repr__(self):
223n/a attrs = {k: v for k, v in self.__dict__.items() if v != '??'}
224n/a if not self.char:
225n/a del attrs['char']
226n/a elif self.char != '??':
227n/a attrs['char'] = repr(self.char)
228n/a if not getattr(self, 'send_event', True):
229n/a del attrs['send_event']
230n/a if self.state == 0:
231n/a del attrs['state']
232n/a elif isinstance(self.state, int):
233n/a state = self.state
234n/a mods = ('Shift', 'Lock', 'Control',
235n/a 'Mod1', 'Mod2', 'Mod3', 'Mod4', 'Mod5',
236n/a 'Button1', 'Button2', 'Button3', 'Button4', 'Button5')
237n/a s = []
238n/a for i, n in enumerate(mods):
239n/a if state & (1 << i):
240n/a s.append(n)
241n/a state = state & ~((1<< len(mods)) - 1)
242n/a if state or not s:
243n/a s.append(hex(state))
244n/a attrs['state'] = '|'.join(s)
245n/a if self.delta == 0:
246n/a del attrs['delta']
247n/a # widget usually is known
248n/a # serial and time are not very interesting
249n/a # keysym_num duplicates keysym
250n/a # x_root and y_root mostly duplicate x and y
251n/a keys = ('send_event',
252n/a 'state', 'keysym', 'keycode', 'char',
253n/a 'num', 'delta', 'focus',
254n/a 'x', 'y', 'width', 'height')
255n/a return '<%s event%s>' % (
256n/a self.type,
257n/a ''.join(' %s=%s' % (k, attrs[k]) for k in keys if k in attrs)
258n/a )
259n/a
260n/a_support_default_root = 1
261n/a_default_root = None
262n/a
263n/adef NoDefaultRoot():
264n/a """Inhibit setting of default root window.
265n/a
266n/a Call this function to inhibit that the first instance of
267n/a Tk is used for windows without an explicit parent window.
268n/a """
269n/a global _support_default_root
270n/a _support_default_root = 0
271n/a global _default_root
272n/a _default_root = None
273n/a del _default_root
274n/a
275n/adef _tkerror(err):
276n/a """Internal function."""
277n/a pass
278n/a
279n/adef _exit(code=0):
280n/a """Internal function. Calling it will raise the exception SystemExit."""
281n/a try:
282n/a code = int(code)
283n/a except ValueError:
284n/a pass
285n/a raise SystemExit(code)
286n/a
287n/a_varnum = 0
288n/aclass Variable:
289n/a """Class to define value holders for e.g. buttons.
290n/a
291n/a Subclasses StringVar, IntVar, DoubleVar, BooleanVar are specializations
292n/a that constrain the type of the value returned from get()."""
293n/a _default = ""
294n/a _tk = None
295n/a _tclCommands = None
296n/a def __init__(self, master=None, value=None, name=None):
297n/a """Construct a variable
298n/a
299n/a MASTER can be given as master widget.
300n/a VALUE is an optional value (defaults to "")
301n/a NAME is an optional Tcl name (defaults to PY_VARnum).
302n/a
303n/a If NAME matches an existing variable and VALUE is omitted
304n/a then the existing value is retained.
305n/a """
306n/a # check for type of NAME parameter to override weird error message
307n/a # raised from Modules/_tkinter.c:SetVar like:
308n/a # TypeError: setvar() takes exactly 3 arguments (2 given)
309n/a if name is not None and not isinstance(name, str):
310n/a raise TypeError("name must be a string")
311n/a global _varnum
312n/a if not master:
313n/a master = _default_root
314n/a self._root = master._root()
315n/a self._tk = master.tk
316n/a if name:
317n/a self._name = name
318n/a else:
319n/a self._name = 'PY_VAR' + repr(_varnum)
320n/a _varnum += 1
321n/a if value is not None:
322n/a self.initialize(value)
323n/a elif not self._tk.getboolean(self._tk.call("info", "exists", self._name)):
324n/a self.initialize(self._default)
325n/a def __del__(self):
326n/a """Unset the variable in Tcl."""
327n/a if self._tk is None:
328n/a return
329n/a if self._tk.getboolean(self._tk.call("info", "exists", self._name)):
330n/a self._tk.globalunsetvar(self._name)
331n/a if self._tclCommands is not None:
332n/a for name in self._tclCommands:
333n/a #print '- Tkinter: deleted command', name
334n/a self._tk.deletecommand(name)
335n/a self._tclCommands = None
336n/a def __str__(self):
337n/a """Return the name of the variable in Tcl."""
338n/a return self._name
339n/a def set(self, value):
340n/a """Set the variable to VALUE."""
341n/a return self._tk.globalsetvar(self._name, value)
342n/a initialize = set
343n/a def get(self):
344n/a """Return value of variable."""
345n/a return self._tk.globalgetvar(self._name)
346n/a
347n/a def _register(self, callback):
348n/a f = CallWrapper(callback, None, self._root).__call__
349n/a cbname = repr(id(f))
350n/a try:
351n/a callback = callback.__func__
352n/a except AttributeError:
353n/a pass
354n/a try:
355n/a cbname = cbname + callback.__name__
356n/a except AttributeError:
357n/a pass
358n/a self._tk.createcommand(cbname, f)
359n/a if self._tclCommands is None:
360n/a self._tclCommands = []
361n/a self._tclCommands.append(cbname)
362n/a return cbname
363n/a
364n/a def trace_add(self, mode, callback):
365n/a """Define a trace callback for the variable.
366n/a
367n/a Mode is one of "read", "write", "unset", or a list or tuple of
368n/a such strings.
369n/a Callback must be a function which is called when the variable is
370n/a read, written or unset.
371n/a
372n/a Return the name of the callback.
373n/a """
374n/a cbname = self._register(callback)
375n/a self._tk.call('trace', 'add', 'variable',
376n/a self._name, mode, (cbname,))
377n/a return cbname
378n/a
379n/a def trace_remove(self, mode, cbname):
380n/a """Delete the trace callback for a variable.
381n/a
382n/a Mode is one of "read", "write", "unset" or a list or tuple of
383n/a such strings. Must be same as were specified in trace_add().
384n/a cbname is the name of the callback returned from trace_add().
385n/a """
386n/a self._tk.call('trace', 'remove', 'variable',
387n/a self._name, mode, cbname)
388n/a for m, ca in self.trace_info():
389n/a if self._tk.splitlist(ca)[0] == cbname:
390n/a break
391n/a else:
392n/a self._tk.deletecommand(cbname)
393n/a try:
394n/a self._tclCommands.remove(cbname)
395n/a except ValueError:
396n/a pass
397n/a
398n/a def trace_info(self):
399n/a """Return all trace callback information."""
400n/a splitlist = self._tk.splitlist
401n/a return [(splitlist(k), v) for k, v in map(splitlist,
402n/a splitlist(self._tk.call('trace', 'info', 'variable', self._name)))]
403n/a
404n/a def trace_variable(self, mode, callback):
405n/a """Define a trace callback for the variable.
406n/a
407n/a MODE is one of "r", "w", "u" for read, write, undefine.
408n/a CALLBACK must be a function which is called when
409n/a the variable is read, written or undefined.
410n/a
411n/a Return the name of the callback.
412n/a
413n/a This deprecated method wraps a deprecated Tcl method that will
414n/a likely be removed in the future. Use trace_add() instead.
415n/a """
416n/a # TODO: Add deprecation warning
417n/a cbname = self._register(callback)
418n/a self._tk.call("trace", "variable", self._name, mode, cbname)
419n/a return cbname
420n/a
421n/a trace = trace_variable
422n/a
423n/a def trace_vdelete(self, mode, cbname):
424n/a """Delete the trace callback for a variable.
425n/a
426n/a MODE is one of "r", "w", "u" for read, write, undefine.
427n/a CBNAME is the name of the callback returned from trace_variable or trace.
428n/a
429n/a This deprecated method wraps a deprecated Tcl method that will
430n/a likely be removed in the future. Use trace_remove() instead.
431n/a """
432n/a # TODO: Add deprecation warning
433n/a self._tk.call("trace", "vdelete", self._name, mode, cbname)
434n/a cbname = self._tk.splitlist(cbname)[0]
435n/a for m, ca in self.trace_info():
436n/a if self._tk.splitlist(ca)[0] == cbname:
437n/a break
438n/a else:
439n/a self._tk.deletecommand(cbname)
440n/a try:
441n/a self._tclCommands.remove(cbname)
442n/a except ValueError:
443n/a pass
444n/a
445n/a def trace_vinfo(self):
446n/a """Return all trace callback information.
447n/a
448n/a This deprecated method wraps a deprecated Tcl method that will
449n/a likely be removed in the future. Use trace_info() instead.
450n/a """
451n/a # TODO: Add deprecation warning
452n/a return [self._tk.splitlist(x) for x in self._tk.splitlist(
453n/a self._tk.call("trace", "vinfo", self._name))]
454n/a
455n/a def __eq__(self, other):
456n/a """Comparison for equality (==).
457n/a
458n/a Note: if the Variable's master matters to behavior
459n/a also compare self._master == other._master
460n/a """
461n/a return self.__class__.__name__ == other.__class__.__name__ \
462n/a and self._name == other._name
463n/a
464n/aclass StringVar(Variable):
465n/a """Value holder for strings variables."""
466n/a _default = ""
467n/a def __init__(self, master=None, value=None, name=None):
468n/a """Construct a string variable.
469n/a
470n/a MASTER can be given as master widget.
471n/a VALUE is an optional value (defaults to "")
472n/a NAME is an optional Tcl name (defaults to PY_VARnum).
473n/a
474n/a If NAME matches an existing variable and VALUE is omitted
475n/a then the existing value is retained.
476n/a """
477n/a Variable.__init__(self, master, value, name)
478n/a
479n/a def get(self):
480n/a """Return value of variable as string."""
481n/a value = self._tk.globalgetvar(self._name)
482n/a if isinstance(value, str):
483n/a return value
484n/a return str(value)
485n/a
486n/aclass IntVar(Variable):
487n/a """Value holder for integer variables."""
488n/a _default = 0
489n/a def __init__(self, master=None, value=None, name=None):
490n/a """Construct an integer variable.
491n/a
492n/a MASTER can be given as master widget.
493n/a VALUE is an optional value (defaults to 0)
494n/a NAME is an optional Tcl name (defaults to PY_VARnum).
495n/a
496n/a If NAME matches an existing variable and VALUE is omitted
497n/a then the existing value is retained.
498n/a """
499n/a Variable.__init__(self, master, value, name)
500n/a
501n/a def get(self):
502n/a """Return the value of the variable as an integer."""
503n/a value = self._tk.globalgetvar(self._name)
504n/a try:
505n/a return self._tk.getint(value)
506n/a except (TypeError, TclError):
507n/a return int(self._tk.getdouble(value))
508n/a
509n/aclass DoubleVar(Variable):
510n/a """Value holder for float variables."""
511n/a _default = 0.0
512n/a def __init__(self, master=None, value=None, name=None):
513n/a """Construct a float variable.
514n/a
515n/a MASTER can be given as master widget.
516n/a VALUE is an optional value (defaults to 0.0)
517n/a NAME is an optional Tcl name (defaults to PY_VARnum).
518n/a
519n/a If NAME matches an existing variable and VALUE is omitted
520n/a then the existing value is retained.
521n/a """
522n/a Variable.__init__(self, master, value, name)
523n/a
524n/a def get(self):
525n/a """Return the value of the variable as a float."""
526n/a return self._tk.getdouble(self._tk.globalgetvar(self._name))
527n/a
528n/aclass BooleanVar(Variable):
529n/a """Value holder for boolean variables."""
530n/a _default = False
531n/a def __init__(self, master=None, value=None, name=None):
532n/a """Construct a boolean variable.
533n/a
534n/a MASTER can be given as master widget.
535n/a VALUE is an optional value (defaults to False)
536n/a NAME is an optional Tcl name (defaults to PY_VARnum).
537n/a
538n/a If NAME matches an existing variable and VALUE is omitted
539n/a then the existing value is retained.
540n/a """
541n/a Variable.__init__(self, master, value, name)
542n/a
543n/a def set(self, value):
544n/a """Set the variable to VALUE."""
545n/a return self._tk.globalsetvar(self._name, self._tk.getboolean(value))
546n/a initialize = set
547n/a
548n/a def get(self):
549n/a """Return the value of the variable as a bool."""
550n/a try:
551n/a return self._tk.getboolean(self._tk.globalgetvar(self._name))
552n/a except TclError:
553n/a raise ValueError("invalid literal for getboolean()")
554n/a
555n/adef mainloop(n=0):
556n/a """Run the main loop of Tcl."""
557n/a _default_root.tk.mainloop(n)
558n/a
559n/agetint = int
560n/a
561n/agetdouble = float
562n/a
563n/adef getboolean(s):
564n/a """Convert true and false to integer values 1 and 0."""
565n/a try:
566n/a return _default_root.tk.getboolean(s)
567n/a except TclError:
568n/a raise ValueError("invalid literal for getboolean()")
569n/a
570n/a# Methods defined on both toplevel and interior widgets
571n/aclass Misc:
572n/a """Internal class.
573n/a
574n/a Base class which defines methods common for interior widgets."""
575n/a
576n/a # used for generating child widget names
577n/a _last_child_ids = None
578n/a
579n/a # XXX font command?
580n/a _tclCommands = None
581n/a def destroy(self):
582n/a """Internal function.
583n/a
584n/a Delete all Tcl commands created for
585n/a this widget in the Tcl interpreter."""
586n/a if self._tclCommands is not None:
587n/a for name in self._tclCommands:
588n/a #print '- Tkinter: deleted command', name
589n/a self.tk.deletecommand(name)
590n/a self._tclCommands = None
591n/a def deletecommand(self, name):
592n/a """Internal function.
593n/a
594n/a Delete the Tcl command provided in NAME."""
595n/a #print '- Tkinter: deleted command', name
596n/a self.tk.deletecommand(name)
597n/a try:
598n/a self._tclCommands.remove(name)
599n/a except ValueError:
600n/a pass
601n/a def tk_strictMotif(self, boolean=None):
602n/a """Set Tcl internal variable, whether the look and feel
603n/a should adhere to Motif.
604n/a
605n/a A parameter of 1 means adhere to Motif (e.g. no color
606n/a change if mouse passes over slider).
607n/a Returns the set value."""
608n/a return self.tk.getboolean(self.tk.call(
609n/a 'set', 'tk_strictMotif', boolean))
610n/a def tk_bisque(self):
611n/a """Change the color scheme to light brown as used in Tk 3.6 and before."""
612n/a self.tk.call('tk_bisque')
613n/a def tk_setPalette(self, *args, **kw):
614n/a """Set a new color scheme for all widget elements.
615n/a
616n/a A single color as argument will cause that all colors of Tk
617n/a widget elements are derived from this.
618n/a Alternatively several keyword parameters and its associated
619n/a colors can be given. The following keywords are valid:
620n/a activeBackground, foreground, selectColor,
621n/a activeForeground, highlightBackground, selectBackground,
622n/a background, highlightColor, selectForeground,
623n/a disabledForeground, insertBackground, troughColor."""
624n/a self.tk.call(('tk_setPalette',)
625n/a + _flatten(args) + _flatten(list(kw.items())))
626n/a def wait_variable(self, name='PY_VAR'):
627n/a """Wait until the variable is modified.
628n/a
629n/a A parameter of type IntVar, StringVar, DoubleVar or
630n/a BooleanVar must be given."""
631n/a self.tk.call('tkwait', 'variable', name)
632n/a waitvar = wait_variable # XXX b/w compat
633n/a def wait_window(self, window=None):
634n/a """Wait until a WIDGET is destroyed.
635n/a
636n/a If no parameter is given self is used."""
637n/a if window is None:
638n/a window = self
639n/a self.tk.call('tkwait', 'window', window._w)
640n/a def wait_visibility(self, window=None):
641n/a """Wait until the visibility of a WIDGET changes
642n/a (e.g. it appears).
643n/a
644n/a If no parameter is given self is used."""
645n/a if window is None:
646n/a window = self
647n/a self.tk.call('tkwait', 'visibility', window._w)
648n/a def setvar(self, name='PY_VAR', value='1'):
649n/a """Set Tcl variable NAME to VALUE."""
650n/a self.tk.setvar(name, value)
651n/a def getvar(self, name='PY_VAR'):
652n/a """Return value of Tcl variable NAME."""
653n/a return self.tk.getvar(name)
654n/a
655n/a def getint(self, s):
656n/a try:
657n/a return self.tk.getint(s)
658n/a except TclError as exc:
659n/a raise ValueError(str(exc))
660n/a
661n/a def getdouble(self, s):
662n/a try:
663n/a return self.tk.getdouble(s)
664n/a except TclError as exc:
665n/a raise ValueError(str(exc))
666n/a
667n/a def getboolean(self, s):
668n/a """Return a boolean value for Tcl boolean values true and false given as parameter."""
669n/a try:
670n/a return self.tk.getboolean(s)
671n/a except TclError:
672n/a raise ValueError("invalid literal for getboolean()")
673n/a
674n/a def focus_set(self):
675n/a """Direct input focus to this widget.
676n/a
677n/a If the application currently does not have the focus
678n/a this widget will get the focus if the application gets
679n/a the focus through the window manager."""
680n/a self.tk.call('focus', self._w)
681n/a focus = focus_set # XXX b/w compat?
682n/a def focus_force(self):
683n/a """Direct input focus to this widget even if the
684n/a application does not have the focus. Use with
685n/a caution!"""
686n/a self.tk.call('focus', '-force', self._w)
687n/a def focus_get(self):
688n/a """Return the widget which has currently the focus in the
689n/a application.
690n/a
691n/a Use focus_displayof to allow working with several
692n/a displays. Return None if application does not have
693n/a the focus."""
694n/a name = self.tk.call('focus')
695n/a if name == 'none' or not name: return None
696n/a return self._nametowidget(name)
697n/a def focus_displayof(self):
698n/a """Return the widget which has currently the focus on the
699n/a display where this widget is located.
700n/a
701n/a Return None if the application does not have the focus."""
702n/a name = self.tk.call('focus', '-displayof', self._w)
703n/a if name == 'none' or not name: return None
704n/a return self._nametowidget(name)
705n/a def focus_lastfor(self):
706n/a """Return the widget which would have the focus if top level
707n/a for this widget gets the focus from the window manager."""
708n/a name = self.tk.call('focus', '-lastfor', self._w)
709n/a if name == 'none' or not name: return None
710n/a return self._nametowidget(name)
711n/a def tk_focusFollowsMouse(self):
712n/a """The widget under mouse will get automatically focus. Can not
713n/a be disabled easily."""
714n/a self.tk.call('tk_focusFollowsMouse')
715n/a def tk_focusNext(self):
716n/a """Return the next widget in the focus order which follows
717n/a widget which has currently the focus.
718n/a
719n/a The focus order first goes to the next child, then to
720n/a the children of the child recursively and then to the
721n/a next sibling which is higher in the stacking order. A
722n/a widget is omitted if it has the takefocus resource set
723n/a to 0."""
724n/a name = self.tk.call('tk_focusNext', self._w)
725n/a if not name: return None
726n/a return self._nametowidget(name)
727n/a def tk_focusPrev(self):
728n/a """Return previous widget in the focus order. See tk_focusNext for details."""
729n/a name = self.tk.call('tk_focusPrev', self._w)
730n/a if not name: return None
731n/a return self._nametowidget(name)
732n/a def after(self, ms, func=None, *args):
733n/a """Call function once after given time.
734n/a
735n/a MS specifies the time in milliseconds. FUNC gives the
736n/a function which shall be called. Additional parameters
737n/a are given as parameters to the function call. Return
738n/a identifier to cancel scheduling with after_cancel."""
739n/a if not func:
740n/a # I'd rather use time.sleep(ms*0.001)
741n/a self.tk.call('after', ms)
742n/a else:
743n/a def callit():
744n/a try:
745n/a func(*args)
746n/a finally:
747n/a try:
748n/a self.deletecommand(name)
749n/a except TclError:
750n/a pass
751n/a callit.__name__ = func.__name__
752n/a name = self._register(callit)
753n/a return self.tk.call('after', ms, name)
754n/a def after_idle(self, func, *args):
755n/a """Call FUNC once if the Tcl main loop has no event to
756n/a process.
757n/a
758n/a Return an identifier to cancel the scheduling with
759n/a after_cancel."""
760n/a return self.after('idle', func, *args)
761n/a def after_cancel(self, id):
762n/a """Cancel scheduling of function identified with ID.
763n/a
764n/a Identifier returned by after or after_idle must be
765n/a given as first parameter."""
766n/a try:
767n/a data = self.tk.call('after', 'info', id)
768n/a # In Tk 8.3, splitlist returns: (script, type)
769n/a # In Tk 8.4, splitlist may return (script, type) or (script,)
770n/a script = self.tk.splitlist(data)[0]
771n/a self.deletecommand(script)
772n/a except TclError:
773n/a pass
774n/a self.tk.call('after', 'cancel', id)
775n/a def bell(self, displayof=0):
776n/a """Ring a display's bell."""
777n/a self.tk.call(('bell',) + self._displayof(displayof))
778n/a
779n/a # Clipboard handling:
780n/a def clipboard_get(self, **kw):
781n/a """Retrieve data from the clipboard on window's display.
782n/a
783n/a The window keyword defaults to the root window of the Tkinter
784n/a application.
785n/a
786n/a The type keyword specifies the form in which the data is
787n/a to be returned and should be an atom name such as STRING
788n/a or FILE_NAME. Type defaults to STRING, except on X11, where the default
789n/a is to try UTF8_STRING and fall back to STRING.
790n/a
791n/a This command is equivalent to:
792n/a
793n/a selection_get(CLIPBOARD)
794n/a """
795n/a if 'type' not in kw and self._windowingsystem == 'x11':
796n/a try:
797n/a kw['type'] = 'UTF8_STRING'
798n/a return self.tk.call(('clipboard', 'get') + self._options(kw))
799n/a except TclError:
800n/a del kw['type']
801n/a return self.tk.call(('clipboard', 'get') + self._options(kw))
802n/a
803n/a def clipboard_clear(self, **kw):
804n/a """Clear the data in the Tk clipboard.
805n/a
806n/a A widget specified for the optional displayof keyword
807n/a argument specifies the target display."""
808n/a if 'displayof' not in kw: kw['displayof'] = self._w
809n/a self.tk.call(('clipboard', 'clear') + self._options(kw))
810n/a def clipboard_append(self, string, **kw):
811n/a """Append STRING to the Tk clipboard.
812n/a
813n/a A widget specified at the optional displayof keyword
814n/a argument specifies the target display. The clipboard
815n/a can be retrieved with selection_get."""
816n/a if 'displayof' not in kw: kw['displayof'] = self._w
817n/a self.tk.call(('clipboard', 'append') + self._options(kw)
818n/a + ('--', string))
819n/a # XXX grab current w/o window argument
820n/a def grab_current(self):
821n/a """Return widget which has currently the grab in this application
822n/a or None."""
823n/a name = self.tk.call('grab', 'current', self._w)
824n/a if not name: return None
825n/a return self._nametowidget(name)
826n/a def grab_release(self):
827n/a """Release grab for this widget if currently set."""
828n/a self.tk.call('grab', 'release', self._w)
829n/a def grab_set(self):
830n/a """Set grab for this widget.
831n/a
832n/a A grab directs all events to this and descendant
833n/a widgets in the application."""
834n/a self.tk.call('grab', 'set', self._w)
835n/a def grab_set_global(self):
836n/a """Set global grab for this widget.
837n/a
838n/a A global grab directs all events to this and
839n/a descendant widgets on the display. Use with caution -
840n/a other applications do not get events anymore."""
841n/a self.tk.call('grab', 'set', '-global', self._w)
842n/a def grab_status(self):
843n/a """Return None, "local" or "global" if this widget has
844n/a no, a local or a global grab."""
845n/a status = self.tk.call('grab', 'status', self._w)
846n/a if status == 'none': status = None
847n/a return status
848n/a def option_add(self, pattern, value, priority = None):
849n/a """Set a VALUE (second parameter) for an option
850n/a PATTERN (first parameter).
851n/a
852n/a An optional third parameter gives the numeric priority
853n/a (defaults to 80)."""
854n/a self.tk.call('option', 'add', pattern, value, priority)
855n/a def option_clear(self):
856n/a """Clear the option database.
857n/a
858n/a It will be reloaded if option_add is called."""
859n/a self.tk.call('option', 'clear')
860n/a def option_get(self, name, className):
861n/a """Return the value for an option NAME for this widget
862n/a with CLASSNAME.
863n/a
864n/a Values with higher priority override lower values."""
865n/a return self.tk.call('option', 'get', self._w, name, className)
866n/a def option_readfile(self, fileName, priority = None):
867n/a """Read file FILENAME into the option database.
868n/a
869n/a An optional second parameter gives the numeric
870n/a priority."""
871n/a self.tk.call('option', 'readfile', fileName, priority)
872n/a def selection_clear(self, **kw):
873n/a """Clear the current X selection."""
874n/a if 'displayof' not in kw: kw['displayof'] = self._w
875n/a self.tk.call(('selection', 'clear') + self._options(kw))
876n/a def selection_get(self, **kw):
877n/a """Return the contents of the current X selection.
878n/a
879n/a A keyword parameter selection specifies the name of
880n/a the selection and defaults to PRIMARY. A keyword
881n/a parameter displayof specifies a widget on the display
882n/a to use. A keyword parameter type specifies the form of data to be
883n/a fetched, defaulting to STRING except on X11, where UTF8_STRING is tried
884n/a before STRING."""
885n/a if 'displayof' not in kw: kw['displayof'] = self._w
886n/a if 'type' not in kw and self._windowingsystem == 'x11':
887n/a try:
888n/a kw['type'] = 'UTF8_STRING'
889n/a return self.tk.call(('selection', 'get') + self._options(kw))
890n/a except TclError:
891n/a del kw['type']
892n/a return self.tk.call(('selection', 'get') + self._options(kw))
893n/a def selection_handle(self, command, **kw):
894n/a """Specify a function COMMAND to call if the X
895n/a selection owned by this widget is queried by another
896n/a application.
897n/a
898n/a This function must return the contents of the
899n/a selection. The function will be called with the
900n/a arguments OFFSET and LENGTH which allows the chunking
901n/a of very long selections. The following keyword
902n/a parameters can be provided:
903n/a selection - name of the selection (default PRIMARY),
904n/a type - type of the selection (e.g. STRING, FILE_NAME)."""
905n/a name = self._register(command)
906n/a self.tk.call(('selection', 'handle') + self._options(kw)
907n/a + (self._w, name))
908n/a def selection_own(self, **kw):
909n/a """Become owner of X selection.
910n/a
911n/a A keyword parameter selection specifies the name of
912n/a the selection (default PRIMARY)."""
913n/a self.tk.call(('selection', 'own') +
914n/a self._options(kw) + (self._w,))
915n/a def selection_own_get(self, **kw):
916n/a """Return owner of X selection.
917n/a
918n/a The following keyword parameter can
919n/a be provided:
920n/a selection - name of the selection (default PRIMARY),
921n/a type - type of the selection (e.g. STRING, FILE_NAME)."""
922n/a if 'displayof' not in kw: kw['displayof'] = self._w
923n/a name = self.tk.call(('selection', 'own') + self._options(kw))
924n/a if not name: return None
925n/a return self._nametowidget(name)
926n/a def send(self, interp, cmd, *args):
927n/a """Send Tcl command CMD to different interpreter INTERP to be executed."""
928n/a return self.tk.call(('send', interp, cmd) + args)
929n/a def lower(self, belowThis=None):
930n/a """Lower this widget in the stacking order."""
931n/a self.tk.call('lower', self._w, belowThis)
932n/a def tkraise(self, aboveThis=None):
933n/a """Raise this widget in the stacking order."""
934n/a self.tk.call('raise', self._w, aboveThis)
935n/a lift = tkraise
936n/a def winfo_atom(self, name, displayof=0):
937n/a """Return integer which represents atom NAME."""
938n/a args = ('winfo', 'atom') + self._displayof(displayof) + (name,)
939n/a return self.tk.getint(self.tk.call(args))
940n/a def winfo_atomname(self, id, displayof=0):
941n/a """Return name of atom with identifier ID."""
942n/a args = ('winfo', 'atomname') \
943n/a + self._displayof(displayof) + (id,)
944n/a return self.tk.call(args)
945n/a def winfo_cells(self):
946n/a """Return number of cells in the colormap for this widget."""
947n/a return self.tk.getint(
948n/a self.tk.call('winfo', 'cells', self._w))
949n/a def winfo_children(self):
950n/a """Return a list of all widgets which are children of this widget."""
951n/a result = []
952n/a for child in self.tk.splitlist(
953n/a self.tk.call('winfo', 'children', self._w)):
954n/a try:
955n/a # Tcl sometimes returns extra windows, e.g. for
956n/a # menus; those need to be skipped
957n/a result.append(self._nametowidget(child))
958n/a except KeyError:
959n/a pass
960n/a return result
961n/a
962n/a def winfo_class(self):
963n/a """Return window class name of this widget."""
964n/a return self.tk.call('winfo', 'class', self._w)
965n/a def winfo_colormapfull(self):
966n/a """Return true if at the last color request the colormap was full."""
967n/a return self.tk.getboolean(
968n/a self.tk.call('winfo', 'colormapfull', self._w))
969n/a def winfo_containing(self, rootX, rootY, displayof=0):
970n/a """Return the widget which is at the root coordinates ROOTX, ROOTY."""
971n/a args = ('winfo', 'containing') \
972n/a + self._displayof(displayof) + (rootX, rootY)
973n/a name = self.tk.call(args)
974n/a if not name: return None
975n/a return self._nametowidget(name)
976n/a def winfo_depth(self):
977n/a """Return the number of bits per pixel."""
978n/a return self.tk.getint(self.tk.call('winfo', 'depth', self._w))
979n/a def winfo_exists(self):
980n/a """Return true if this widget exists."""
981n/a return self.tk.getint(
982n/a self.tk.call('winfo', 'exists', self._w))
983n/a def winfo_fpixels(self, number):
984n/a """Return the number of pixels for the given distance NUMBER
985n/a (e.g. "3c") as float."""
986n/a return self.tk.getdouble(self.tk.call(
987n/a 'winfo', 'fpixels', self._w, number))
988n/a def winfo_geometry(self):
989n/a """Return geometry string for this widget in the form "widthxheight+X+Y"."""
990n/a return self.tk.call('winfo', 'geometry', self._w)
991n/a def winfo_height(self):
992n/a """Return height of this widget."""
993n/a return self.tk.getint(
994n/a self.tk.call('winfo', 'height', self._w))
995n/a def winfo_id(self):
996n/a """Return identifier ID for this widget."""
997n/a return int(self.tk.call('winfo', 'id', self._w), 0)
998n/a def winfo_interps(self, displayof=0):
999n/a """Return the name of all Tcl interpreters for this display."""
1000n/a args = ('winfo', 'interps') + self._displayof(displayof)
1001n/a return self.tk.splitlist(self.tk.call(args))
1002n/a def winfo_ismapped(self):
1003n/a """Return true if this widget is mapped."""
1004n/a return self.tk.getint(
1005n/a self.tk.call('winfo', 'ismapped', self._w))
1006n/a def winfo_manager(self):
1007n/a """Return the window mananger name for this widget."""
1008n/a return self.tk.call('winfo', 'manager', self._w)
1009n/a def winfo_name(self):
1010n/a """Return the name of this widget."""
1011n/a return self.tk.call('winfo', 'name', self._w)
1012n/a def winfo_parent(self):
1013n/a """Return the name of the parent of this widget."""
1014n/a return self.tk.call('winfo', 'parent', self._w)
1015n/a def winfo_pathname(self, id, displayof=0):
1016n/a """Return the pathname of the widget given by ID."""
1017n/a args = ('winfo', 'pathname') \
1018n/a + self._displayof(displayof) + (id,)
1019n/a return self.tk.call(args)
1020n/a def winfo_pixels(self, number):
1021n/a """Rounded integer value of winfo_fpixels."""
1022n/a return self.tk.getint(
1023n/a self.tk.call('winfo', 'pixels', self._w, number))
1024n/a def winfo_pointerx(self):
1025n/a """Return the x coordinate of the pointer on the root window."""
1026n/a return self.tk.getint(
1027n/a self.tk.call('winfo', 'pointerx', self._w))
1028n/a def winfo_pointerxy(self):
1029n/a """Return a tuple of x and y coordinates of the pointer on the root window."""
1030n/a return self._getints(
1031n/a self.tk.call('winfo', 'pointerxy', self._w))
1032n/a def winfo_pointery(self):
1033n/a """Return the y coordinate of the pointer on the root window."""
1034n/a return self.tk.getint(
1035n/a self.tk.call('winfo', 'pointery', self._w))
1036n/a def winfo_reqheight(self):
1037n/a """Return requested height of this widget."""
1038n/a return self.tk.getint(
1039n/a self.tk.call('winfo', 'reqheight', self._w))
1040n/a def winfo_reqwidth(self):
1041n/a """Return requested width of this widget."""
1042n/a return self.tk.getint(
1043n/a self.tk.call('winfo', 'reqwidth', self._w))
1044n/a def winfo_rgb(self, color):
1045n/a """Return tuple of decimal values for red, green, blue for
1046n/a COLOR in this widget."""
1047n/a return self._getints(
1048n/a self.tk.call('winfo', 'rgb', self._w, color))
1049n/a def winfo_rootx(self):
1050n/a """Return x coordinate of upper left corner of this widget on the
1051n/a root window."""
1052n/a return self.tk.getint(
1053n/a self.tk.call('winfo', 'rootx', self._w))
1054n/a def winfo_rooty(self):
1055n/a """Return y coordinate of upper left corner of this widget on the
1056n/a root window."""
1057n/a return self.tk.getint(
1058n/a self.tk.call('winfo', 'rooty', self._w))
1059n/a def winfo_screen(self):
1060n/a """Return the screen name of this widget."""
1061n/a return self.tk.call('winfo', 'screen', self._w)
1062n/a def winfo_screencells(self):
1063n/a """Return the number of the cells in the colormap of the screen
1064n/a of this widget."""
1065n/a return self.tk.getint(
1066n/a self.tk.call('winfo', 'screencells', self._w))
1067n/a def winfo_screendepth(self):
1068n/a """Return the number of bits per pixel of the root window of the
1069n/a screen of this widget."""
1070n/a return self.tk.getint(
1071n/a self.tk.call('winfo', 'screendepth', self._w))
1072n/a def winfo_screenheight(self):
1073n/a """Return the number of pixels of the height of the screen of this widget
1074n/a in pixel."""
1075n/a return self.tk.getint(
1076n/a self.tk.call('winfo', 'screenheight', self._w))
1077n/a def winfo_screenmmheight(self):
1078n/a """Return the number of pixels of the height of the screen of
1079n/a this widget in mm."""
1080n/a return self.tk.getint(
1081n/a self.tk.call('winfo', 'screenmmheight', self._w))
1082n/a def winfo_screenmmwidth(self):
1083n/a """Return the number of pixels of the width of the screen of
1084n/a this widget in mm."""
1085n/a return self.tk.getint(
1086n/a self.tk.call('winfo', 'screenmmwidth', self._w))
1087n/a def winfo_screenvisual(self):
1088n/a """Return one of the strings directcolor, grayscale, pseudocolor,
1089n/a staticcolor, staticgray, or truecolor for the default
1090n/a colormodel of this screen."""
1091n/a return self.tk.call('winfo', 'screenvisual', self._w)
1092n/a def winfo_screenwidth(self):
1093n/a """Return the number of pixels of the width of the screen of
1094n/a this widget in pixel."""
1095n/a return self.tk.getint(
1096n/a self.tk.call('winfo', 'screenwidth', self._w))
1097n/a def winfo_server(self):
1098n/a """Return information of the X-Server of the screen of this widget in
1099n/a the form "XmajorRminor vendor vendorVersion"."""
1100n/a return self.tk.call('winfo', 'server', self._w)
1101n/a def winfo_toplevel(self):
1102n/a """Return the toplevel widget of this widget."""
1103n/a return self._nametowidget(self.tk.call(
1104n/a 'winfo', 'toplevel', self._w))
1105n/a def winfo_viewable(self):
1106n/a """Return true if the widget and all its higher ancestors are mapped."""
1107n/a return self.tk.getint(
1108n/a self.tk.call('winfo', 'viewable', self._w))
1109n/a def winfo_visual(self):
1110n/a """Return one of the strings directcolor, grayscale, pseudocolor,
1111n/a staticcolor, staticgray, or truecolor for the
1112n/a colormodel of this widget."""
1113n/a return self.tk.call('winfo', 'visual', self._w)
1114n/a def winfo_visualid(self):
1115n/a """Return the X identifier for the visual for this widget."""
1116n/a return self.tk.call('winfo', 'visualid', self._w)
1117n/a def winfo_visualsavailable(self, includeids=False):
1118n/a """Return a list of all visuals available for the screen
1119n/a of this widget.
1120n/a
1121n/a Each item in the list consists of a visual name (see winfo_visual), a
1122n/a depth and if includeids is true is given also the X identifier."""
1123n/a data = self.tk.call('winfo', 'visualsavailable', self._w,
1124n/a 'includeids' if includeids else None)
1125n/a data = [self.tk.splitlist(x) for x in self.tk.splitlist(data)]
1126n/a return [self.__winfo_parseitem(x) for x in data]
1127n/a def __winfo_parseitem(self, t):
1128n/a """Internal function."""
1129n/a return t[:1] + tuple(map(self.__winfo_getint, t[1:]))
1130n/a def __winfo_getint(self, x):
1131n/a """Internal function."""
1132n/a return int(x, 0)
1133n/a def winfo_vrootheight(self):
1134n/a """Return the height of the virtual root window associated with this
1135n/a widget in pixels. If there is no virtual root window return the
1136n/a height of the screen."""
1137n/a return self.tk.getint(
1138n/a self.tk.call('winfo', 'vrootheight', self._w))
1139n/a def winfo_vrootwidth(self):
1140n/a """Return the width of the virtual root window associated with this
1141n/a widget in pixel. If there is no virtual root window return the
1142n/a width of the screen."""
1143n/a return self.tk.getint(
1144n/a self.tk.call('winfo', 'vrootwidth', self._w))
1145n/a def winfo_vrootx(self):
1146n/a """Return the x offset of the virtual root relative to the root
1147n/a window of the screen of this widget."""
1148n/a return self.tk.getint(
1149n/a self.tk.call('winfo', 'vrootx', self._w))
1150n/a def winfo_vrooty(self):
1151n/a """Return the y offset of the virtual root relative to the root
1152n/a window of the screen of this widget."""
1153n/a return self.tk.getint(
1154n/a self.tk.call('winfo', 'vrooty', self._w))
1155n/a def winfo_width(self):
1156n/a """Return the width of this widget."""
1157n/a return self.tk.getint(
1158n/a self.tk.call('winfo', 'width', self._w))
1159n/a def winfo_x(self):
1160n/a """Return the x coordinate of the upper left corner of this widget
1161n/a in the parent."""
1162n/a return self.tk.getint(
1163n/a self.tk.call('winfo', 'x', self._w))
1164n/a def winfo_y(self):
1165n/a """Return the y coordinate of the upper left corner of this widget
1166n/a in the parent."""
1167n/a return self.tk.getint(
1168n/a self.tk.call('winfo', 'y', self._w))
1169n/a def update(self):
1170n/a """Enter event loop until all pending events have been processed by Tcl."""
1171n/a self.tk.call('update')
1172n/a def update_idletasks(self):
1173n/a """Enter event loop until all idle callbacks have been called. This
1174n/a will update the display of windows but not process events caused by
1175n/a the user."""
1176n/a self.tk.call('update', 'idletasks')
1177n/a def bindtags(self, tagList=None):
1178n/a """Set or get the list of bindtags for this widget.
1179n/a
1180n/a With no argument return the list of all bindtags associated with
1181n/a this widget. With a list of strings as argument the bindtags are
1182n/a set to this list. The bindtags determine in which order events are
1183n/a processed (see bind)."""
1184n/a if tagList is None:
1185n/a return self.tk.splitlist(
1186n/a self.tk.call('bindtags', self._w))
1187n/a else:
1188n/a self.tk.call('bindtags', self._w, tagList)
1189n/a def _bind(self, what, sequence, func, add, needcleanup=1):
1190n/a """Internal function."""
1191n/a if isinstance(func, str):
1192n/a self.tk.call(what + (sequence, func))
1193n/a elif func:
1194n/a funcid = self._register(func, self._substitute,
1195n/a needcleanup)
1196n/a cmd = ('%sif {"[%s %s]" == "break"} break\n'
1197n/a %
1198n/a (add and '+' or '',
1199n/a funcid, self._subst_format_str))
1200n/a self.tk.call(what + (sequence, cmd))
1201n/a return funcid
1202n/a elif sequence:
1203n/a return self.tk.call(what + (sequence,))
1204n/a else:
1205n/a return self.tk.splitlist(self.tk.call(what))
1206n/a def bind(self, sequence=None, func=None, add=None):
1207n/a """Bind to this widget at event SEQUENCE a call to function FUNC.
1208n/a
1209n/a SEQUENCE is a string of concatenated event
1210n/a patterns. An event pattern is of the form
1211n/a <MODIFIER-MODIFIER-TYPE-DETAIL> where MODIFIER is one
1212n/a of Control, Mod2, M2, Shift, Mod3, M3, Lock, Mod4, M4,
1213n/a Button1, B1, Mod5, M5 Button2, B2, Meta, M, Button3,
1214n/a B3, Alt, Button4, B4, Double, Button5, B5 Triple,
1215n/a Mod1, M1. TYPE is one of Activate, Enter, Map,
1216n/a ButtonPress, Button, Expose, Motion, ButtonRelease
1217n/a FocusIn, MouseWheel, Circulate, FocusOut, Property,
1218n/a Colormap, Gravity Reparent, Configure, KeyPress, Key,
1219n/a Unmap, Deactivate, KeyRelease Visibility, Destroy,
1220n/a Leave and DETAIL is the button number for ButtonPress,
1221n/a ButtonRelease and DETAIL is the Keysym for KeyPress and
1222n/a KeyRelease. Examples are
1223n/a <Control-Button-1> for pressing Control and mouse button 1 or
1224n/a <Alt-A> for pressing A and the Alt key (KeyPress can be omitted).
1225n/a An event pattern can also be a virtual event of the form
1226n/a <<AString>> where AString can be arbitrary. This
1227n/a event can be generated by event_generate.
1228n/a If events are concatenated they must appear shortly
1229n/a after each other.
1230n/a
1231n/a FUNC will be called if the event sequence occurs with an
1232n/a instance of Event as argument. If the return value of FUNC is
1233n/a "break" no further bound function is invoked.
1234n/a
1235n/a An additional boolean parameter ADD specifies whether FUNC will
1236n/a be called additionally to the other bound function or whether
1237n/a it will replace the previous function.
1238n/a
1239n/a Bind will return an identifier to allow deletion of the bound function with
1240n/a unbind without memory leak.
1241n/a
1242n/a If FUNC or SEQUENCE is omitted the bound function or list
1243n/a of bound events are returned."""
1244n/a
1245n/a return self._bind(('bind', self._w), sequence, func, add)
1246n/a def unbind(self, sequence, funcid=None):
1247n/a """Unbind for this widget for event SEQUENCE the
1248n/a function identified with FUNCID."""
1249n/a self.tk.call('bind', self._w, sequence, '')
1250n/a if funcid:
1251n/a self.deletecommand(funcid)
1252n/a def bind_all(self, sequence=None, func=None, add=None):
1253n/a """Bind to all widgets at an event SEQUENCE a call to function FUNC.
1254n/a An additional boolean parameter ADD specifies whether FUNC will
1255n/a be called additionally to the other bound function or whether
1256n/a it will replace the previous function. See bind for the return value."""
1257n/a return self._bind(('bind', 'all'), sequence, func, add, 0)
1258n/a def unbind_all(self, sequence):
1259n/a """Unbind for all widgets for event SEQUENCE all functions."""
1260n/a self.tk.call('bind', 'all' , sequence, '')
1261n/a def bind_class(self, className, sequence=None, func=None, add=None):
1262n/a
1263n/a """Bind to widgets with bindtag CLASSNAME at event
1264n/a SEQUENCE a call of function FUNC. An additional
1265n/a boolean parameter ADD specifies whether FUNC will be
1266n/a called additionally to the other bound function or
1267n/a whether it will replace the previous function. See bind for
1268n/a the return value."""
1269n/a
1270n/a return self._bind(('bind', className), sequence, func, add, 0)
1271n/a def unbind_class(self, className, sequence):
1272n/a """Unbind for all widgets with bindtag CLASSNAME for event SEQUENCE
1273n/a all functions."""
1274n/a self.tk.call('bind', className , sequence, '')
1275n/a def mainloop(self, n=0):
1276n/a """Call the mainloop of Tk."""
1277n/a self.tk.mainloop(n)
1278n/a def quit(self):
1279n/a """Quit the Tcl interpreter. All widgets will be destroyed."""
1280n/a self.tk.quit()
1281n/a def _getints(self, string):
1282n/a """Internal function."""
1283n/a if string:
1284n/a return tuple(map(self.tk.getint, self.tk.splitlist(string)))
1285n/a def _getdoubles(self, string):
1286n/a """Internal function."""
1287n/a if string:
1288n/a return tuple(map(self.tk.getdouble, self.tk.splitlist(string)))
1289n/a def _getboolean(self, string):
1290n/a """Internal function."""
1291n/a if string:
1292n/a return self.tk.getboolean(string)
1293n/a def _displayof(self, displayof):
1294n/a """Internal function."""
1295n/a if displayof:
1296n/a return ('-displayof', displayof)
1297n/a if displayof is None:
1298n/a return ('-displayof', self._w)
1299n/a return ()
1300n/a @property
1301n/a def _windowingsystem(self):
1302n/a """Internal function."""
1303n/a try:
1304n/a return self._root()._windowingsystem_cached
1305n/a except AttributeError:
1306n/a ws = self._root()._windowingsystem_cached = \
1307n/a self.tk.call('tk', 'windowingsystem')
1308n/a return ws
1309n/a def _options(self, cnf, kw = None):
1310n/a """Internal function."""
1311n/a if kw:
1312n/a cnf = _cnfmerge((cnf, kw))
1313n/a else:
1314n/a cnf = _cnfmerge(cnf)
1315n/a res = ()
1316n/a for k, v in cnf.items():
1317n/a if v is not None:
1318n/a if k[-1] == '_': k = k[:-1]
1319n/a if callable(v):
1320n/a v = self._register(v)
1321n/a elif isinstance(v, (tuple, list)):
1322n/a nv = []
1323n/a for item in v:
1324n/a if isinstance(item, int):
1325n/a nv.append(str(item))
1326n/a elif isinstance(item, str):
1327n/a nv.append(_stringify(item))
1328n/a else:
1329n/a break
1330n/a else:
1331n/a v = ' '.join(nv)
1332n/a res = res + ('-'+k, v)
1333n/a return res
1334n/a def nametowidget(self, name):
1335n/a """Return the Tkinter instance of a widget identified by
1336n/a its Tcl name NAME."""
1337n/a name = str(name).split('.')
1338n/a w = self
1339n/a
1340n/a if not name[0]:
1341n/a w = w._root()
1342n/a name = name[1:]
1343n/a
1344n/a for n in name:
1345n/a if not n:
1346n/a break
1347n/a w = w.children[n]
1348n/a
1349n/a return w
1350n/a _nametowidget = nametowidget
1351n/a def _register(self, func, subst=None, needcleanup=1):
1352n/a """Return a newly created Tcl function. If this
1353n/a function is called, the Python function FUNC will
1354n/a be executed. An optional function SUBST can
1355n/a be given which will be executed before FUNC."""
1356n/a f = CallWrapper(func, subst, self).__call__
1357n/a name = repr(id(f))
1358n/a try:
1359n/a func = func.__func__
1360n/a except AttributeError:
1361n/a pass
1362n/a try:
1363n/a name = name + func.__name__
1364n/a except AttributeError:
1365n/a pass
1366n/a self.tk.createcommand(name, f)
1367n/a if needcleanup:
1368n/a if self._tclCommands is None:
1369n/a self._tclCommands = []
1370n/a self._tclCommands.append(name)
1371n/a return name
1372n/a register = _register
1373n/a def _root(self):
1374n/a """Internal function."""
1375n/a w = self
1376n/a while w.master: w = w.master
1377n/a return w
1378n/a _subst_format = ('%#', '%b', '%f', '%h', '%k',
1379n/a '%s', '%t', '%w', '%x', '%y',
1380n/a '%A', '%E', '%K', '%N', '%W', '%T', '%X', '%Y', '%D')
1381n/a _subst_format_str = " ".join(_subst_format)
1382n/a def _substitute(self, *args):
1383n/a """Internal function."""
1384n/a if len(args) != len(self._subst_format): return args
1385n/a getboolean = self.tk.getboolean
1386n/a
1387n/a getint = self.tk.getint
1388n/a def getint_event(s):
1389n/a """Tk changed behavior in 8.4.2, returning "??" rather more often."""
1390n/a try:
1391n/a return getint(s)
1392n/a except (ValueError, TclError):
1393n/a return s
1394n/a
1395n/a nsign, b, f, h, k, s, t, w, x, y, A, E, K, N, W, T, X, Y, D = args
1396n/a # Missing: (a, c, d, m, o, v, B, R)
1397n/a e = Event()
1398n/a # serial field: valid for all events
1399n/a # number of button: ButtonPress and ButtonRelease events only
1400n/a # height field: Configure, ConfigureRequest, Create,
1401n/a # ResizeRequest, and Expose events only
1402n/a # keycode field: KeyPress and KeyRelease events only
1403n/a # time field: "valid for events that contain a time field"
1404n/a # width field: Configure, ConfigureRequest, Create, ResizeRequest,
1405n/a # and Expose events only
1406n/a # x field: "valid for events that contain an x field"
1407n/a # y field: "valid for events that contain a y field"
1408n/a # keysym as decimal: KeyPress and KeyRelease events only
1409n/a # x_root, y_root fields: ButtonPress, ButtonRelease, KeyPress,
1410n/a # KeyRelease, and Motion events
1411n/a e.serial = getint(nsign)
1412n/a e.num = getint_event(b)
1413n/a try: e.focus = getboolean(f)
1414n/a except TclError: pass
1415n/a e.height = getint_event(h)
1416n/a e.keycode = getint_event(k)
1417n/a e.state = getint_event(s)
1418n/a e.time = getint_event(t)
1419n/a e.width = getint_event(w)
1420n/a e.x = getint_event(x)
1421n/a e.y = getint_event(y)
1422n/a e.char = A
1423n/a try: e.send_event = getboolean(E)
1424n/a except TclError: pass
1425n/a e.keysym = K
1426n/a e.keysym_num = getint_event(N)
1427n/a try:
1428n/a e.type = EventType(T)
1429n/a except ValueError:
1430n/a e.type = T
1431n/a try:
1432n/a e.widget = self._nametowidget(W)
1433n/a except KeyError:
1434n/a e.widget = W
1435n/a e.x_root = getint_event(X)
1436n/a e.y_root = getint_event(Y)
1437n/a try:
1438n/a e.delta = getint(D)
1439n/a except (ValueError, TclError):
1440n/a e.delta = 0
1441n/a return (e,)
1442n/a def _report_exception(self):
1443n/a """Internal function."""
1444n/a exc, val, tb = sys.exc_info()
1445n/a root = self._root()
1446n/a root.report_callback_exception(exc, val, tb)
1447n/a
1448n/a def _getconfigure(self, *args):
1449n/a """Call Tcl configure command and return the result as a dict."""
1450n/a cnf = {}
1451n/a for x in self.tk.splitlist(self.tk.call(*args)):
1452n/a x = self.tk.splitlist(x)
1453n/a cnf[x[0][1:]] = (x[0][1:],) + x[1:]
1454n/a return cnf
1455n/a
1456n/a def _getconfigure1(self, *args):
1457n/a x = self.tk.splitlist(self.tk.call(*args))
1458n/a return (x[0][1:],) + x[1:]
1459n/a
1460n/a def _configure(self, cmd, cnf, kw):
1461n/a """Internal function."""
1462n/a if kw:
1463n/a cnf = _cnfmerge((cnf, kw))
1464n/a elif cnf:
1465n/a cnf = _cnfmerge(cnf)
1466n/a if cnf is None:
1467n/a return self._getconfigure(_flatten((self._w, cmd)))
1468n/a if isinstance(cnf, str):
1469n/a return self._getconfigure1(_flatten((self._w, cmd, '-'+cnf)))
1470n/a self.tk.call(_flatten((self._w, cmd)) + self._options(cnf))
1471n/a # These used to be defined in Widget:
1472n/a def configure(self, cnf=None, **kw):
1473n/a """Configure resources of a widget.
1474n/a
1475n/a The values for resources are specified as keyword
1476n/a arguments. To get an overview about
1477n/a the allowed keyword arguments call the method keys.
1478n/a """
1479n/a return self._configure('configure', cnf, kw)
1480n/a config = configure
1481n/a def cget(self, key):
1482n/a """Return the resource value for a KEY given as string."""
1483n/a return self.tk.call(self._w, 'cget', '-' + key)
1484n/a __getitem__ = cget
1485n/a def __setitem__(self, key, value):
1486n/a self.configure({key: value})
1487n/a def keys(self):
1488n/a """Return a list of all resource names of this widget."""
1489n/a splitlist = self.tk.splitlist
1490n/a return [splitlist(x)[0][1:] for x in
1491n/a splitlist(self.tk.call(self._w, 'configure'))]
1492n/a def __str__(self):
1493n/a """Return the window path name of this widget."""
1494n/a return self._w
1495n/a
1496n/a def __repr__(self):
1497n/a return '<%s.%s object %s>' % (
1498n/a self.__class__.__module__, self.__class__.__qualname__, self._w)
1499n/a
1500n/a # Pack methods that apply to the master
1501n/a _noarg_ = ['_noarg_']
1502n/a def pack_propagate(self, flag=_noarg_):
1503n/a """Set or get the status for propagation of geometry information.
1504n/a
1505n/a A boolean argument specifies whether the geometry information
1506n/a of the slaves will determine the size of this widget. If no argument
1507n/a is given the current setting will be returned.
1508n/a """
1509n/a if flag is Misc._noarg_:
1510n/a return self._getboolean(self.tk.call(
1511n/a 'pack', 'propagate', self._w))
1512n/a else:
1513n/a self.tk.call('pack', 'propagate', self._w, flag)
1514n/a propagate = pack_propagate
1515n/a def pack_slaves(self):
1516n/a """Return a list of all slaves of this widget
1517n/a in its packing order."""
1518n/a return [self._nametowidget(x) for x in
1519n/a self.tk.splitlist(
1520n/a self.tk.call('pack', 'slaves', self._w))]
1521n/a slaves = pack_slaves
1522n/a # Place method that applies to the master
1523n/a def place_slaves(self):
1524n/a """Return a list of all slaves of this widget
1525n/a in its packing order."""
1526n/a return [self._nametowidget(x) for x in
1527n/a self.tk.splitlist(
1528n/a self.tk.call(
1529n/a 'place', 'slaves', self._w))]
1530n/a # Grid methods that apply to the master
1531n/a def grid_anchor(self, anchor=None): # new in Tk 8.5
1532n/a """The anchor value controls how to place the grid within the
1533n/a master when no row/column has any weight.
1534n/a
1535n/a The default anchor is nw."""
1536n/a self.tk.call('grid', 'anchor', self._w, anchor)
1537n/a anchor = grid_anchor
1538n/a def grid_bbox(self, column=None, row=None, col2=None, row2=None):
1539n/a """Return a tuple of integer coordinates for the bounding
1540n/a box of this widget controlled by the geometry manager grid.
1541n/a
1542n/a If COLUMN, ROW is given the bounding box applies from
1543n/a the cell with row and column 0 to the specified
1544n/a cell. If COL2 and ROW2 are given the bounding box
1545n/a starts at that cell.
1546n/a
1547n/a The returned integers specify the offset of the upper left
1548n/a corner in the master widget and the width and height.
1549n/a """
1550n/a args = ('grid', 'bbox', self._w)
1551n/a if column is not None and row is not None:
1552n/a args = args + (column, row)
1553n/a if col2 is not None and row2 is not None:
1554n/a args = args + (col2, row2)
1555n/a return self._getints(self.tk.call(*args)) or None
1556n/a bbox = grid_bbox
1557n/a
1558n/a def _gridconvvalue(self, value):
1559n/a if isinstance(value, (str, _tkinter.Tcl_Obj)):
1560n/a try:
1561n/a svalue = str(value)
1562n/a if not svalue:
1563n/a return None
1564n/a elif '.' in svalue:
1565n/a return self.tk.getdouble(svalue)
1566n/a else:
1567n/a return self.tk.getint(svalue)
1568n/a except (ValueError, TclError):
1569n/a pass
1570n/a return value
1571n/a
1572n/a def _grid_configure(self, command, index, cnf, kw):
1573n/a """Internal function."""
1574n/a if isinstance(cnf, str) and not kw:
1575n/a if cnf[-1:] == '_':
1576n/a cnf = cnf[:-1]
1577n/a if cnf[:1] != '-':
1578n/a cnf = '-'+cnf
1579n/a options = (cnf,)
1580n/a else:
1581n/a options = self._options(cnf, kw)
1582n/a if not options:
1583n/a return _splitdict(
1584n/a self.tk,
1585n/a self.tk.call('grid', command, self._w, index),
1586n/a conv=self._gridconvvalue)
1587n/a res = self.tk.call(
1588n/a ('grid', command, self._w, index)
1589n/a + options)
1590n/a if len(options) == 1:
1591n/a return self._gridconvvalue(res)
1592n/a
1593n/a def grid_columnconfigure(self, index, cnf={}, **kw):
1594n/a """Configure column INDEX of a grid.
1595n/a
1596n/a Valid resources are minsize (minimum size of the column),
1597n/a weight (how much does additional space propagate to this column)
1598n/a and pad (how much space to let additionally)."""
1599n/a return self._grid_configure('columnconfigure', index, cnf, kw)
1600n/a columnconfigure = grid_columnconfigure
1601n/a def grid_location(self, x, y):
1602n/a """Return a tuple of column and row which identify the cell
1603n/a at which the pixel at position X and Y inside the master
1604n/a widget is located."""
1605n/a return self._getints(
1606n/a self.tk.call(
1607n/a 'grid', 'location', self._w, x, y)) or None
1608n/a def grid_propagate(self, flag=_noarg_):
1609n/a """Set or get the status for propagation of geometry information.
1610n/a
1611n/a A boolean argument specifies whether the geometry information
1612n/a of the slaves will determine the size of this widget. If no argument
1613n/a is given, the current setting will be returned.
1614n/a """
1615n/a if flag is Misc._noarg_:
1616n/a return self._getboolean(self.tk.call(
1617n/a 'grid', 'propagate', self._w))
1618n/a else:
1619n/a self.tk.call('grid', 'propagate', self._w, flag)
1620n/a def grid_rowconfigure(self, index, cnf={}, **kw):
1621n/a """Configure row INDEX of a grid.
1622n/a
1623n/a Valid resources are minsize (minimum size of the row),
1624n/a weight (how much does additional space propagate to this row)
1625n/a and pad (how much space to let additionally)."""
1626n/a return self._grid_configure('rowconfigure', index, cnf, kw)
1627n/a rowconfigure = grid_rowconfigure
1628n/a def grid_size(self):
1629n/a """Return a tuple of the number of column and rows in the grid."""
1630n/a return self._getints(
1631n/a self.tk.call('grid', 'size', self._w)) or None
1632n/a size = grid_size
1633n/a def grid_slaves(self, row=None, column=None):
1634n/a """Return a list of all slaves of this widget
1635n/a in its packing order."""
1636n/a args = ()
1637n/a if row is not None:
1638n/a args = args + ('-row', row)
1639n/a if column is not None:
1640n/a args = args + ('-column', column)
1641n/a return [self._nametowidget(x) for x in
1642n/a self.tk.splitlist(self.tk.call(
1643n/a ('grid', 'slaves', self._w) + args))]
1644n/a
1645n/a # Support for the "event" command, new in Tk 4.2.
1646n/a # By Case Roole.
1647n/a
1648n/a def event_add(self, virtual, *sequences):
1649n/a """Bind a virtual event VIRTUAL (of the form <<Name>>)
1650n/a to an event SEQUENCE such that the virtual event is triggered
1651n/a whenever SEQUENCE occurs."""
1652n/a args = ('event', 'add', virtual) + sequences
1653n/a self.tk.call(args)
1654n/a
1655n/a def event_delete(self, virtual, *sequences):
1656n/a """Unbind a virtual event VIRTUAL from SEQUENCE."""
1657n/a args = ('event', 'delete', virtual) + sequences
1658n/a self.tk.call(args)
1659n/a
1660n/a def event_generate(self, sequence, **kw):
1661n/a """Generate an event SEQUENCE. Additional
1662n/a keyword arguments specify parameter of the event
1663n/a (e.g. x, y, rootx, rooty)."""
1664n/a args = ('event', 'generate', self._w, sequence)
1665n/a for k, v in kw.items():
1666n/a args = args + ('-%s' % k, str(v))
1667n/a self.tk.call(args)
1668n/a
1669n/a def event_info(self, virtual=None):
1670n/a """Return a list of all virtual events or the information
1671n/a about the SEQUENCE bound to the virtual event VIRTUAL."""
1672n/a return self.tk.splitlist(
1673n/a self.tk.call('event', 'info', virtual))
1674n/a
1675n/a # Image related commands
1676n/a
1677n/a def image_names(self):
1678n/a """Return a list of all existing image names."""
1679n/a return self.tk.splitlist(self.tk.call('image', 'names'))
1680n/a
1681n/a def image_types(self):
1682n/a """Return a list of all available image types (e.g. phote bitmap)."""
1683n/a return self.tk.splitlist(self.tk.call('image', 'types'))
1684n/a
1685n/a
1686n/aclass CallWrapper:
1687n/a """Internal class. Stores function to call when some user
1688n/a defined Tcl function is called e.g. after an event occurred."""
1689n/a def __init__(self, func, subst, widget):
1690n/a """Store FUNC, SUBST and WIDGET as members."""
1691n/a self.func = func
1692n/a self.subst = subst
1693n/a self.widget = widget
1694n/a def __call__(self, *args):
1695n/a """Apply first function SUBST to arguments, than FUNC."""
1696n/a try:
1697n/a if self.subst:
1698n/a args = self.subst(*args)
1699n/a return self.func(*args)
1700n/a except SystemExit:
1701n/a raise
1702n/a except:
1703n/a self.widget._report_exception()
1704n/a
1705n/a
1706n/aclass XView:
1707n/a """Mix-in class for querying and changing the horizontal position
1708n/a of a widget's window."""
1709n/a
1710n/a def xview(self, *args):
1711n/a """Query and change the horizontal position of the view."""
1712n/a res = self.tk.call(self._w, 'xview', *args)
1713n/a if not args:
1714n/a return self._getdoubles(res)
1715n/a
1716n/a def xview_moveto(self, fraction):
1717n/a """Adjusts the view in the window so that FRACTION of the
1718n/a total width of the canvas is off-screen to the left."""
1719n/a self.tk.call(self._w, 'xview', 'moveto', fraction)
1720n/a
1721n/a def xview_scroll(self, number, what):
1722n/a """Shift the x-view according to NUMBER which is measured in "units"
1723n/a or "pages" (WHAT)."""
1724n/a self.tk.call(self._w, 'xview', 'scroll', number, what)
1725n/a
1726n/a
1727n/aclass YView:
1728n/a """Mix-in class for querying and changing the vertical position
1729n/a of a widget's window."""
1730n/a
1731n/a def yview(self, *args):
1732n/a """Query and change the vertical position of the view."""
1733n/a res = self.tk.call(self._w, 'yview', *args)
1734n/a if not args:
1735n/a return self._getdoubles(res)
1736n/a
1737n/a def yview_moveto(self, fraction):
1738n/a """Adjusts the view in the window so that FRACTION of the
1739n/a total height of the canvas is off-screen to the top."""
1740n/a self.tk.call(self._w, 'yview', 'moveto', fraction)
1741n/a
1742n/a def yview_scroll(self, number, what):
1743n/a """Shift the y-view according to NUMBER which is measured in
1744n/a "units" or "pages" (WHAT)."""
1745n/a self.tk.call(self._w, 'yview', 'scroll', number, what)
1746n/a
1747n/a
1748n/aclass Wm:
1749n/a """Provides functions for the communication with the window manager."""
1750n/a
1751n/a def wm_aspect(self,
1752n/a minNumer=None, minDenom=None,
1753n/a maxNumer=None, maxDenom=None):
1754n/a """Instruct the window manager to set the aspect ratio (width/height)
1755n/a of this widget to be between MINNUMER/MINDENOM and MAXNUMER/MAXDENOM. Return a tuple
1756n/a of the actual values if no argument is given."""
1757n/a return self._getints(
1758n/a self.tk.call('wm', 'aspect', self._w,
1759n/a minNumer, minDenom,
1760n/a maxNumer, maxDenom))
1761n/a aspect = wm_aspect
1762n/a
1763n/a def wm_attributes(self, *args):
1764n/a """This subcommand returns or sets platform specific attributes
1765n/a
1766n/a The first form returns a list of the platform specific flags and
1767n/a their values. The second form returns the value for the specific
1768n/a option. The third form sets one or more of the values. The values
1769n/a are as follows:
1770n/a
1771n/a On Windows, -disabled gets or sets whether the window is in a
1772n/a disabled state. -toolwindow gets or sets the style of the window
1773n/a to toolwindow (as defined in the MSDN). -topmost gets or sets
1774n/a whether this is a topmost window (displays above all other
1775n/a windows).
1776n/a
1777n/a On Macintosh, XXXXX
1778n/a
1779n/a On Unix, there are currently no special attribute values.
1780n/a """
1781n/a args = ('wm', 'attributes', self._w) + args
1782n/a return self.tk.call(args)
1783n/a attributes=wm_attributes
1784n/a
1785n/a def wm_client(self, name=None):
1786n/a """Store NAME in WM_CLIENT_MACHINE property of this widget. Return
1787n/a current value."""
1788n/a return self.tk.call('wm', 'client', self._w, name)
1789n/a client = wm_client
1790n/a def wm_colormapwindows(self, *wlist):
1791n/a """Store list of window names (WLIST) into WM_COLORMAPWINDOWS property
1792n/a of this widget. This list contains windows whose colormaps differ from their
1793n/a parents. Return current list of widgets if WLIST is empty."""
1794n/a if len(wlist) > 1:
1795n/a wlist = (wlist,) # Tk needs a list of windows here
1796n/a args = ('wm', 'colormapwindows', self._w) + wlist
1797n/a if wlist:
1798n/a self.tk.call(args)
1799n/a else:
1800n/a return [self._nametowidget(x)
1801n/a for x in self.tk.splitlist(self.tk.call(args))]
1802n/a colormapwindows = wm_colormapwindows
1803n/a def wm_command(self, value=None):
1804n/a """Store VALUE in WM_COMMAND property. It is the command
1805n/a which shall be used to invoke the application. Return current
1806n/a command if VALUE is None."""
1807n/a return self.tk.call('wm', 'command', self._w, value)
1808n/a command = wm_command
1809n/a def wm_deiconify(self):
1810n/a """Deiconify this widget. If it was never mapped it will not be mapped.
1811n/a On Windows it will raise this widget and give it the focus."""
1812n/a return self.tk.call('wm', 'deiconify', self._w)
1813n/a deiconify = wm_deiconify
1814n/a def wm_focusmodel(self, model=None):
1815n/a """Set focus model to MODEL. "active" means that this widget will claim
1816n/a the focus itself, "passive" means that the window manager shall give
1817n/a the focus. Return current focus model if MODEL is None."""
1818n/a return self.tk.call('wm', 'focusmodel', self._w, model)
1819n/a focusmodel = wm_focusmodel
1820n/a def wm_forget(self, window): # new in Tk 8.5
1821n/a """The window will be unmappend from the screen and will no longer
1822n/a be managed by wm. toplevel windows will be treated like frame
1823n/a windows once they are no longer managed by wm, however, the menu
1824n/a option configuration will be remembered and the menus will return
1825n/a once the widget is managed again."""
1826n/a self.tk.call('wm', 'forget', window)
1827n/a forget = wm_forget
1828n/a def wm_frame(self):
1829n/a """Return identifier for decorative frame of this widget if present."""
1830n/a return self.tk.call('wm', 'frame', self._w)
1831n/a frame = wm_frame
1832n/a def wm_geometry(self, newGeometry=None):
1833n/a """Set geometry to NEWGEOMETRY of the form =widthxheight+x+y. Return
1834n/a current value if None is given."""
1835n/a return self.tk.call('wm', 'geometry', self._w, newGeometry)
1836n/a geometry = wm_geometry
1837n/a def wm_grid(self,
1838n/a baseWidth=None, baseHeight=None,
1839n/a widthInc=None, heightInc=None):
1840n/a """Instruct the window manager that this widget shall only be
1841n/a resized on grid boundaries. WIDTHINC and HEIGHTINC are the width and
1842n/a height of a grid unit in pixels. BASEWIDTH and BASEHEIGHT are the
1843n/a number of grid units requested in Tk_GeometryRequest."""
1844n/a return self._getints(self.tk.call(
1845n/a 'wm', 'grid', self._w,
1846n/a baseWidth, baseHeight, widthInc, heightInc))
1847n/a grid = wm_grid
1848n/a def wm_group(self, pathName=None):
1849n/a """Set the group leader widgets for related widgets to PATHNAME. Return
1850n/a the group leader of this widget if None is given."""
1851n/a return self.tk.call('wm', 'group', self._w, pathName)
1852n/a group = wm_group
1853n/a def wm_iconbitmap(self, bitmap=None, default=None):
1854n/a """Set bitmap for the iconified widget to BITMAP. Return
1855n/a the bitmap if None is given.
1856n/a
1857n/a Under Windows, the DEFAULT parameter can be used to set the icon
1858n/a for the widget and any descendents that don't have an icon set
1859n/a explicitly. DEFAULT can be the relative path to a .ico file
1860n/a (example: root.iconbitmap(default='myicon.ico') ). See Tk
1861n/a documentation for more information."""
1862n/a if default:
1863n/a return self.tk.call('wm', 'iconbitmap', self._w, '-default', default)
1864n/a else:
1865n/a return self.tk.call('wm', 'iconbitmap', self._w, bitmap)
1866n/a iconbitmap = wm_iconbitmap
1867n/a def wm_iconify(self):
1868n/a """Display widget as icon."""
1869n/a return self.tk.call('wm', 'iconify', self._w)
1870n/a iconify = wm_iconify
1871n/a def wm_iconmask(self, bitmap=None):
1872n/a """Set mask for the icon bitmap of this widget. Return the
1873n/a mask if None is given."""
1874n/a return self.tk.call('wm', 'iconmask', self._w, bitmap)
1875n/a iconmask = wm_iconmask
1876n/a def wm_iconname(self, newName=None):
1877n/a """Set the name of the icon for this widget. Return the name if
1878n/a None is given."""
1879n/a return self.tk.call('wm', 'iconname', self._w, newName)
1880n/a iconname = wm_iconname
1881n/a def wm_iconphoto(self, default=False, *args): # new in Tk 8.5
1882n/a """Sets the titlebar icon for this window based on the named photo
1883n/a images passed through args. If default is True, this is applied to
1884n/a all future created toplevels as well.
1885n/a
1886n/a The data in the images is taken as a snapshot at the time of
1887n/a invocation. If the images are later changed, this is not reflected
1888n/a to the titlebar icons. Multiple images are accepted to allow
1889n/a different images sizes to be provided. The window manager may scale
1890n/a provided icons to an appropriate size.
1891n/a
1892n/a On Windows, the images are packed into a Windows icon structure.
1893n/a This will override an icon specified to wm_iconbitmap, and vice
1894n/a versa.
1895n/a
1896n/a On X, the images are arranged into the _NET_WM_ICON X property,
1897n/a which most modern window managers support. An icon specified by
1898n/a wm_iconbitmap may exist simultaneously.
1899n/a
1900n/a On Macintosh, this currently does nothing."""
1901n/a if default:
1902n/a self.tk.call('wm', 'iconphoto', self._w, "-default", *args)
1903n/a else:
1904n/a self.tk.call('wm', 'iconphoto', self._w, *args)
1905n/a iconphoto = wm_iconphoto
1906n/a def wm_iconposition(self, x=None, y=None):
1907n/a """Set the position of the icon of this widget to X and Y. Return
1908n/a a tuple of the current values of X and X if None is given."""
1909n/a return self._getints(self.tk.call(
1910n/a 'wm', 'iconposition', self._w, x, y))
1911n/a iconposition = wm_iconposition
1912n/a def wm_iconwindow(self, pathName=None):
1913n/a """Set widget PATHNAME to be displayed instead of icon. Return the current
1914n/a value if None is given."""
1915n/a return self.tk.call('wm', 'iconwindow', self._w, pathName)
1916n/a iconwindow = wm_iconwindow
1917n/a def wm_manage(self, widget): # new in Tk 8.5
1918n/a """The widget specified will become a stand alone top-level window.
1919n/a The window will be decorated with the window managers title bar,
1920n/a etc."""
1921n/a self.tk.call('wm', 'manage', widget)
1922n/a manage = wm_manage
1923n/a def wm_maxsize(self, width=None, height=None):
1924n/a """Set max WIDTH and HEIGHT for this widget. If the window is gridded
1925n/a the values are given in grid units. Return the current values if None
1926n/a is given."""
1927n/a return self._getints(self.tk.call(
1928n/a 'wm', 'maxsize', self._w, width, height))
1929n/a maxsize = wm_maxsize
1930n/a def wm_minsize(self, width=None, height=None):
1931n/a """Set min WIDTH and HEIGHT for this widget. If the window is gridded
1932n/a the values are given in grid units. Return the current values if None
1933n/a is given."""
1934n/a return self._getints(self.tk.call(
1935n/a 'wm', 'minsize', self._w, width, height))
1936n/a minsize = wm_minsize
1937n/a def wm_overrideredirect(self, boolean=None):
1938n/a """Instruct the window manager to ignore this widget
1939n/a if BOOLEAN is given with 1. Return the current value if None
1940n/a is given."""
1941n/a return self._getboolean(self.tk.call(
1942n/a 'wm', 'overrideredirect', self._w, boolean))
1943n/a overrideredirect = wm_overrideredirect
1944n/a def wm_positionfrom(self, who=None):
1945n/a """Instruct the window manager that the position of this widget shall
1946n/a be defined by the user if WHO is "user", and by its own policy if WHO is
1947n/a "program"."""
1948n/a return self.tk.call('wm', 'positionfrom', self._w, who)
1949n/a positionfrom = wm_positionfrom
1950n/a def wm_protocol(self, name=None, func=None):
1951n/a """Bind function FUNC to command NAME for this widget.
1952n/a Return the function bound to NAME if None is given. NAME could be
1953n/a e.g. "WM_SAVE_YOURSELF" or "WM_DELETE_WINDOW"."""
1954n/a if callable(func):
1955n/a command = self._register(func)
1956n/a else:
1957n/a command = func
1958n/a return self.tk.call(
1959n/a 'wm', 'protocol', self._w, name, command)
1960n/a protocol = wm_protocol
1961n/a def wm_resizable(self, width=None, height=None):
1962n/a """Instruct the window manager whether this width can be resized
1963n/a in WIDTH or HEIGHT. Both values are boolean values."""
1964n/a return self.tk.call('wm', 'resizable', self._w, width, height)
1965n/a resizable = wm_resizable
1966n/a def wm_sizefrom(self, who=None):
1967n/a """Instruct the window manager that the size of this widget shall
1968n/a be defined by the user if WHO is "user", and by its own policy if WHO is
1969n/a "program"."""
1970n/a return self.tk.call('wm', 'sizefrom', self._w, who)
1971n/a sizefrom = wm_sizefrom
1972n/a def wm_state(self, newstate=None):
1973n/a """Query or set the state of this widget as one of normal, icon,
1974n/a iconic (see wm_iconwindow), withdrawn, or zoomed (Windows only)."""
1975n/a return self.tk.call('wm', 'state', self._w, newstate)
1976n/a state = wm_state
1977n/a def wm_title(self, string=None):
1978n/a """Set the title of this widget."""
1979n/a return self.tk.call('wm', 'title', self._w, string)
1980n/a title = wm_title
1981n/a def wm_transient(self, master=None):
1982n/a """Instruct the window manager that this widget is transient
1983n/a with regard to widget MASTER."""
1984n/a return self.tk.call('wm', 'transient', self._w, master)
1985n/a transient = wm_transient
1986n/a def wm_withdraw(self):
1987n/a """Withdraw this widget from the screen such that it is unmapped
1988n/a and forgotten by the window manager. Re-draw it with wm_deiconify."""
1989n/a return self.tk.call('wm', 'withdraw', self._w)
1990n/a withdraw = wm_withdraw
1991n/a
1992n/a
1993n/aclass Tk(Misc, Wm):
1994n/a """Toplevel widget of Tk which represents mostly the main window
1995n/a of an application. It has an associated Tcl interpreter."""
1996n/a _w = '.'
1997n/a def __init__(self, screenName=None, baseName=None, className='Tk',
1998n/a useTk=1, sync=0, use=None):
1999n/a """Return a new Toplevel widget on screen SCREENNAME. A new Tcl interpreter will
2000n/a be created. BASENAME will be used for the identification of the profile file (see
2001n/a readprofile).
2002n/a It is constructed from sys.argv[0] without extensions if None is given. CLASSNAME
2003n/a is the name of the widget class."""
2004n/a self.master = None
2005n/a self.children = {}
2006n/a self._tkloaded = 0
2007n/a # to avoid recursions in the getattr code in case of failure, we
2008n/a # ensure that self.tk is always _something_.
2009n/a self.tk = None
2010n/a if baseName is None:
2011n/a import os
2012n/a baseName = os.path.basename(sys.argv[0])
2013n/a baseName, ext = os.path.splitext(baseName)
2014n/a if ext not in ('.py', '.pyc'):
2015n/a baseName = baseName + ext
2016n/a interactive = 0
2017n/a self.tk = _tkinter.create(screenName, baseName, className, interactive, wantobjects, useTk, sync, use)
2018n/a if useTk:
2019n/a self._loadtk()
2020n/a if not sys.flags.ignore_environment:
2021n/a # Issue #16248: Honor the -E flag to avoid code injection.
2022n/a self.readprofile(baseName, className)
2023n/a def loadtk(self):
2024n/a if not self._tkloaded:
2025n/a self.tk.loadtk()
2026n/a self._loadtk()
2027n/a def _loadtk(self):
2028n/a self._tkloaded = 1
2029n/a global _default_root
2030n/a # Version sanity checks
2031n/a tk_version = self.tk.getvar('tk_version')
2032n/a if tk_version != _tkinter.TK_VERSION:
2033n/a raise RuntimeError("tk.h version (%s) doesn't match libtk.a version (%s)"
2034n/a % (_tkinter.TK_VERSION, tk_version))
2035n/a # Under unknown circumstances, tcl_version gets coerced to float
2036n/a tcl_version = str(self.tk.getvar('tcl_version'))
2037n/a if tcl_version != _tkinter.TCL_VERSION:
2038n/a raise RuntimeError("tcl.h version (%s) doesn't match libtcl.a version (%s)" \
2039n/a % (_tkinter.TCL_VERSION, tcl_version))
2040n/a # Create and register the tkerror and exit commands
2041n/a # We need to inline parts of _register here, _ register
2042n/a # would register differently-named commands.
2043n/a if self._tclCommands is None:
2044n/a self._tclCommands = []
2045n/a self.tk.createcommand('tkerror', _tkerror)
2046n/a self.tk.createcommand('exit', _exit)
2047n/a self._tclCommands.append('tkerror')
2048n/a self._tclCommands.append('exit')
2049n/a if _support_default_root and not _default_root:
2050n/a _default_root = self
2051n/a self.protocol("WM_DELETE_WINDOW", self.destroy)
2052n/a def destroy(self):
2053n/a """Destroy this and all descendants widgets. This will
2054n/a end the application of this Tcl interpreter."""
2055n/a for c in list(self.children.values()): c.destroy()
2056n/a self.tk.call('destroy', self._w)
2057n/a Misc.destroy(self)
2058n/a global _default_root
2059n/a if _support_default_root and _default_root is self:
2060n/a _default_root = None
2061n/a def readprofile(self, baseName, className):
2062n/a """Internal function. It reads BASENAME.tcl and CLASSNAME.tcl into
2063n/a the Tcl Interpreter and calls exec on the contents of BASENAME.py and
2064n/a CLASSNAME.py if such a file exists in the home directory."""
2065n/a import os
2066n/a if 'HOME' in os.environ: home = os.environ['HOME']
2067n/a else: home = os.curdir
2068n/a class_tcl = os.path.join(home, '.%s.tcl' % className)
2069n/a class_py = os.path.join(home, '.%s.py' % className)
2070n/a base_tcl = os.path.join(home, '.%s.tcl' % baseName)
2071n/a base_py = os.path.join(home, '.%s.py' % baseName)
2072n/a dir = {'self': self}
2073n/a exec('from tkinter import *', dir)
2074n/a if os.path.isfile(class_tcl):
2075n/a self.tk.call('source', class_tcl)
2076n/a if os.path.isfile(class_py):
2077n/a exec(open(class_py).read(), dir)
2078n/a if os.path.isfile(base_tcl):
2079n/a self.tk.call('source', base_tcl)
2080n/a if os.path.isfile(base_py):
2081n/a exec(open(base_py).read(), dir)
2082n/a def report_callback_exception(self, exc, val, tb):
2083n/a """Report callback exception on sys.stderr.
2084n/a
2085n/a Applications may want to override this internal function, and
2086n/a should when sys.stderr is None."""
2087n/a import traceback
2088n/a print("Exception in Tkinter callback", file=sys.stderr)
2089n/a sys.last_type = exc
2090n/a sys.last_value = val
2091n/a sys.last_traceback = tb
2092n/a traceback.print_exception(exc, val, tb)
2093n/a def __getattr__(self, attr):
2094n/a "Delegate attribute access to the interpreter object"
2095n/a return getattr(self.tk, attr)
2096n/a
2097n/a# Ideally, the classes Pack, Place and Grid disappear, the
2098n/a# pack/place/grid methods are defined on the Widget class, and
2099n/a# everybody uses w.pack_whatever(...) instead of Pack.whatever(w,
2100n/a# ...), with pack(), place() and grid() being short for
2101n/a# pack_configure(), place_configure() and grid_columnconfigure(), and
2102n/a# forget() being short for pack_forget(). As a practical matter, I'm
2103n/a# afraid that there is too much code out there that may be using the
2104n/a# Pack, Place or Grid class, so I leave them intact -- but only as
2105n/a# backwards compatibility features. Also note that those methods that
2106n/a# take a master as argument (e.g. pack_propagate) have been moved to
2107n/a# the Misc class (which now incorporates all methods common between
2108n/a# toplevel and interior widgets). Again, for compatibility, these are
2109n/a# copied into the Pack, Place or Grid class.
2110n/a
2111n/a
2112n/adef Tcl(screenName=None, baseName=None, className='Tk', useTk=0):
2113n/a return Tk(screenName, baseName, className, useTk)
2114n/a
2115n/aclass Pack:
2116n/a """Geometry manager Pack.
2117n/a
2118n/a Base class to use the methods pack_* in every widget."""
2119n/a def pack_configure(self, cnf={}, **kw):
2120n/a """Pack a widget in the parent widget. Use as options:
2121n/a after=widget - pack it after you have packed widget
2122n/a anchor=NSEW (or subset) - position widget according to
2123n/a given direction
2124n/a before=widget - pack it before you will pack widget
2125n/a expand=bool - expand widget if parent size grows
2126n/a fill=NONE or X or Y or BOTH - fill widget if widget grows
2127n/a in=master - use master to contain this widget
2128n/a in_=master - see 'in' option description
2129n/a ipadx=amount - add internal padding in x direction
2130n/a ipady=amount - add internal padding in y direction
2131n/a padx=amount - add padding in x direction
2132n/a pady=amount - add padding in y direction
2133n/a side=TOP or BOTTOM or LEFT or RIGHT - where to add this widget.
2134n/a """
2135n/a self.tk.call(
2136n/a ('pack', 'configure', self._w)
2137n/a + self._options(cnf, kw))
2138n/a pack = configure = config = pack_configure
2139n/a def pack_forget(self):
2140n/a """Unmap this widget and do not use it for the packing order."""
2141n/a self.tk.call('pack', 'forget', self._w)
2142n/a forget = pack_forget
2143n/a def pack_info(self):
2144n/a """Return information about the packing options
2145n/a for this widget."""
2146n/a d = _splitdict(self.tk, self.tk.call('pack', 'info', self._w))
2147n/a if 'in' in d:
2148n/a d['in'] = self.nametowidget(d['in'])
2149n/a return d
2150n/a info = pack_info
2151n/a propagate = pack_propagate = Misc.pack_propagate
2152n/a slaves = pack_slaves = Misc.pack_slaves
2153n/a
2154n/aclass Place:
2155n/a """Geometry manager Place.
2156n/a
2157n/a Base class to use the methods place_* in every widget."""
2158n/a def place_configure(self, cnf={}, **kw):
2159n/a """Place a widget in the parent widget. Use as options:
2160n/a in=master - master relative to which the widget is placed
2161n/a in_=master - see 'in' option description
2162n/a x=amount - locate anchor of this widget at position x of master
2163n/a y=amount - locate anchor of this widget at position y of master
2164n/a relx=amount - locate anchor of this widget between 0.0 and 1.0
2165n/a relative to width of master (1.0 is right edge)
2166n/a rely=amount - locate anchor of this widget between 0.0 and 1.0
2167n/a relative to height of master (1.0 is bottom edge)
2168n/a anchor=NSEW (or subset) - position anchor according to given direction
2169n/a width=amount - width of this widget in pixel
2170n/a height=amount - height of this widget in pixel
2171n/a relwidth=amount - width of this widget between 0.0 and 1.0
2172n/a relative to width of master (1.0 is the same width
2173n/a as the master)
2174n/a relheight=amount - height of this widget between 0.0 and 1.0
2175n/a relative to height of master (1.0 is the same
2176n/a height as the master)
2177n/a bordermode="inside" or "outside" - whether to take border width of
2178n/a master widget into account
2179n/a """
2180n/a self.tk.call(
2181n/a ('place', 'configure', self._w)
2182n/a + self._options(cnf, kw))
2183n/a place = configure = config = place_configure
2184n/a def place_forget(self):
2185n/a """Unmap this widget."""
2186n/a self.tk.call('place', 'forget', self._w)
2187n/a forget = place_forget
2188n/a def place_info(self):
2189n/a """Return information about the placing options
2190n/a for this widget."""
2191n/a d = _splitdict(self.tk, self.tk.call('place', 'info', self._w))
2192n/a if 'in' in d:
2193n/a d['in'] = self.nametowidget(d['in'])
2194n/a return d
2195n/a info = place_info
2196n/a slaves = place_slaves = Misc.place_slaves
2197n/a
2198n/aclass Grid:
2199n/a """Geometry manager Grid.
2200n/a
2201n/a Base class to use the methods grid_* in every widget."""
2202n/a # Thanks to Masazumi Yoshikawa (yosikawa@isi.edu)
2203n/a def grid_configure(self, cnf={}, **kw):
2204n/a """Position a widget in the parent widget in a grid. Use as options:
2205n/a column=number - use cell identified with given column (starting with 0)
2206n/a columnspan=number - this widget will span several columns
2207n/a in=master - use master to contain this widget
2208n/a in_=master - see 'in' option description
2209n/a ipadx=amount - add internal padding in x direction
2210n/a ipady=amount - add internal padding in y direction
2211n/a padx=amount - add padding in x direction
2212n/a pady=amount - add padding in y direction
2213n/a row=number - use cell identified with given row (starting with 0)
2214n/a rowspan=number - this widget will span several rows
2215n/a sticky=NSEW - if cell is larger on which sides will this
2216n/a widget stick to the cell boundary
2217n/a """
2218n/a self.tk.call(
2219n/a ('grid', 'configure', self._w)
2220n/a + self._options(cnf, kw))
2221n/a grid = configure = config = grid_configure
2222n/a bbox = grid_bbox = Misc.grid_bbox
2223n/a columnconfigure = grid_columnconfigure = Misc.grid_columnconfigure
2224n/a def grid_forget(self):
2225n/a """Unmap this widget."""
2226n/a self.tk.call('grid', 'forget', self._w)
2227n/a forget = grid_forget
2228n/a def grid_remove(self):
2229n/a """Unmap this widget but remember the grid options."""
2230n/a self.tk.call('grid', 'remove', self._w)
2231n/a def grid_info(self):
2232n/a """Return information about the options
2233n/a for positioning this widget in a grid."""
2234n/a d = _splitdict(self.tk, self.tk.call('grid', 'info', self._w))
2235n/a if 'in' in d:
2236n/a d['in'] = self.nametowidget(d['in'])
2237n/a return d
2238n/a info = grid_info
2239n/a location = grid_location = Misc.grid_location
2240n/a propagate = grid_propagate = Misc.grid_propagate
2241n/a rowconfigure = grid_rowconfigure = Misc.grid_rowconfigure
2242n/a size = grid_size = Misc.grid_size
2243n/a slaves = grid_slaves = Misc.grid_slaves
2244n/a
2245n/aclass BaseWidget(Misc):
2246n/a """Internal class."""
2247n/a def _setup(self, master, cnf):
2248n/a """Internal function. Sets up information about children."""
2249n/a if _support_default_root:
2250n/a global _default_root
2251n/a if not master:
2252n/a if not _default_root:
2253n/a _default_root = Tk()
2254n/a master = _default_root
2255n/a self.master = master
2256n/a self.tk = master.tk
2257n/a name = None
2258n/a if 'name' in cnf:
2259n/a name = cnf['name']
2260n/a del cnf['name']
2261n/a if not name:
2262n/a name = self.__class__.__name__.lower()
2263n/a if master._last_child_ids is None:
2264n/a master._last_child_ids = {}
2265n/a count = master._last_child_ids.get(name, 0) + 1
2266n/a master._last_child_ids[name] = count
2267n/a if count == 1:
2268n/a name = '!%s' % (name,)
2269n/a else:
2270n/a name = '!%s%d' % (name, count)
2271n/a self._name = name
2272n/a if master._w=='.':
2273n/a self._w = '.' + name
2274n/a else:
2275n/a self._w = master._w + '.' + name
2276n/a self.children = {}
2277n/a if self._name in self.master.children:
2278n/a self.master.children[self._name].destroy()
2279n/a self.master.children[self._name] = self
2280n/a def __init__(self, master, widgetName, cnf={}, kw={}, extra=()):
2281n/a """Construct a widget with the parent widget MASTER, a name WIDGETNAME
2282n/a and appropriate options."""
2283n/a if kw:
2284n/a cnf = _cnfmerge((cnf, kw))
2285n/a self.widgetName = widgetName
2286n/a BaseWidget._setup(self, master, cnf)
2287n/a if self._tclCommands is None:
2288n/a self._tclCommands = []
2289n/a classes = [(k, v) for k, v in cnf.items() if isinstance(k, type)]
2290n/a for k, v in classes:
2291n/a del cnf[k]
2292n/a self.tk.call(
2293n/a (widgetName, self._w) + extra + self._options(cnf))
2294n/a for k, v in classes:
2295n/a k.configure(self, v)
2296n/a def destroy(self):
2297n/a """Destroy this and all descendants widgets."""
2298n/a for c in list(self.children.values()): c.destroy()
2299n/a self.tk.call('destroy', self._w)
2300n/a if self._name in self.master.children:
2301n/a del self.master.children[self._name]
2302n/a Misc.destroy(self)
2303n/a def _do(self, name, args=()):
2304n/a # XXX Obsolete -- better use self.tk.call directly!
2305n/a return self.tk.call((self._w, name) + args)
2306n/a
2307n/aclass Widget(BaseWidget, Pack, Place, Grid):
2308n/a """Internal class.
2309n/a
2310n/a Base class for a widget which can be positioned with the geometry managers
2311n/a Pack, Place or Grid."""
2312n/a pass
2313n/a
2314n/aclass Toplevel(BaseWidget, Wm):
2315n/a """Toplevel widget, e.g. for dialogs."""
2316n/a def __init__(self, master=None, cnf={}, **kw):
2317n/a """Construct a toplevel widget with the parent MASTER.
2318n/a
2319n/a Valid resource names: background, bd, bg, borderwidth, class,
2320n/a colormap, container, cursor, height, highlightbackground,
2321n/a highlightcolor, highlightthickness, menu, relief, screen, takefocus,
2322n/a use, visual, width."""
2323n/a if kw:
2324n/a cnf = _cnfmerge((cnf, kw))
2325n/a extra = ()
2326n/a for wmkey in ['screen', 'class_', 'class', 'visual',
2327n/a 'colormap']:
2328n/a if wmkey in cnf:
2329n/a val = cnf[wmkey]
2330n/a # TBD: a hack needed because some keys
2331n/a # are not valid as keyword arguments
2332n/a if wmkey[-1] == '_': opt = '-'+wmkey[:-1]
2333n/a else: opt = '-'+wmkey
2334n/a extra = extra + (opt, val)
2335n/a del cnf[wmkey]
2336n/a BaseWidget.__init__(self, master, 'toplevel', cnf, {}, extra)
2337n/a root = self._root()
2338n/a self.iconname(root.iconname())
2339n/a self.title(root.title())
2340n/a self.protocol("WM_DELETE_WINDOW", self.destroy)
2341n/a
2342n/aclass Button(Widget):
2343n/a """Button widget."""
2344n/a def __init__(self, master=None, cnf={}, **kw):
2345n/a """Construct a button widget with the parent MASTER.
2346n/a
2347n/a STANDARD OPTIONS
2348n/a
2349n/a activebackground, activeforeground, anchor,
2350n/a background, bitmap, borderwidth, cursor,
2351n/a disabledforeground, font, foreground
2352n/a highlightbackground, highlightcolor,
2353n/a highlightthickness, image, justify,
2354n/a padx, pady, relief, repeatdelay,
2355n/a repeatinterval, takefocus, text,
2356n/a textvariable, underline, wraplength
2357n/a
2358n/a WIDGET-SPECIFIC OPTIONS
2359n/a
2360n/a command, compound, default, height,
2361n/a overrelief, state, width
2362n/a """
2363n/a Widget.__init__(self, master, 'button', cnf, kw)
2364n/a
2365n/a def flash(self):
2366n/a """Flash the button.
2367n/a
2368n/a This is accomplished by redisplaying
2369n/a the button several times, alternating between active and
2370n/a normal colors. At the end of the flash the button is left
2371n/a in the same normal/active state as when the command was
2372n/a invoked. This command is ignored if the button's state is
2373n/a disabled.
2374n/a """
2375n/a self.tk.call(self._w, 'flash')
2376n/a
2377n/a def invoke(self):
2378n/a """Invoke the command associated with the button.
2379n/a
2380n/a The return value is the return value from the command,
2381n/a or an empty string if there is no command associated with
2382n/a the button. This command is ignored if the button's state
2383n/a is disabled.
2384n/a """
2385n/a return self.tk.call(self._w, 'invoke')
2386n/a
2387n/aclass Canvas(Widget, XView, YView):
2388n/a """Canvas widget to display graphical elements like lines or text."""
2389n/a def __init__(self, master=None, cnf={}, **kw):
2390n/a """Construct a canvas widget with the parent MASTER.
2391n/a
2392n/a Valid resource names: background, bd, bg, borderwidth, closeenough,
2393n/a confine, cursor, height, highlightbackground, highlightcolor,
2394n/a highlightthickness, insertbackground, insertborderwidth,
2395n/a insertofftime, insertontime, insertwidth, offset, relief,
2396n/a scrollregion, selectbackground, selectborderwidth, selectforeground,
2397n/a state, takefocus, width, xscrollcommand, xscrollincrement,
2398n/a yscrollcommand, yscrollincrement."""
2399n/a Widget.__init__(self, master, 'canvas', cnf, kw)
2400n/a def addtag(self, *args):
2401n/a """Internal function."""
2402n/a self.tk.call((self._w, 'addtag') + args)
2403n/a def addtag_above(self, newtag, tagOrId):
2404n/a """Add tag NEWTAG to all items above TAGORID."""
2405n/a self.addtag(newtag, 'above', tagOrId)
2406n/a def addtag_all(self, newtag):
2407n/a """Add tag NEWTAG to all items."""
2408n/a self.addtag(newtag, 'all')
2409n/a def addtag_below(self, newtag, tagOrId):
2410n/a """Add tag NEWTAG to all items below TAGORID."""
2411n/a self.addtag(newtag, 'below', tagOrId)
2412n/a def addtag_closest(self, newtag, x, y, halo=None, start=None):
2413n/a """Add tag NEWTAG to item which is closest to pixel at X, Y.
2414n/a If several match take the top-most.
2415n/a All items closer than HALO are considered overlapping (all are
2416n/a closests). If START is specified the next below this tag is taken."""
2417n/a self.addtag(newtag, 'closest', x, y, halo, start)
2418n/a def addtag_enclosed(self, newtag, x1, y1, x2, y2):
2419n/a """Add tag NEWTAG to all items in the rectangle defined
2420n/a by X1,Y1,X2,Y2."""
2421n/a self.addtag(newtag, 'enclosed', x1, y1, x2, y2)
2422n/a def addtag_overlapping(self, newtag, x1, y1, x2, y2):
2423n/a """Add tag NEWTAG to all items which overlap the rectangle
2424n/a defined by X1,Y1,X2,Y2."""
2425n/a self.addtag(newtag, 'overlapping', x1, y1, x2, y2)
2426n/a def addtag_withtag(self, newtag, tagOrId):
2427n/a """Add tag NEWTAG to all items with TAGORID."""
2428n/a self.addtag(newtag, 'withtag', tagOrId)
2429n/a def bbox(self, *args):
2430n/a """Return a tuple of X1,Y1,X2,Y2 coordinates for a rectangle
2431n/a which encloses all items with tags specified as arguments."""
2432n/a return self._getints(
2433n/a self.tk.call((self._w, 'bbox') + args)) or None
2434n/a def tag_unbind(self, tagOrId, sequence, funcid=None):
2435n/a """Unbind for all items with TAGORID for event SEQUENCE the
2436n/a function identified with FUNCID."""
2437n/a self.tk.call(self._w, 'bind', tagOrId, sequence, '')
2438n/a if funcid:
2439n/a self.deletecommand(funcid)
2440n/a def tag_bind(self, tagOrId, sequence=None, func=None, add=None):
2441n/a """Bind to all items with TAGORID at event SEQUENCE a call to function FUNC.
2442n/a
2443n/a An additional boolean parameter ADD specifies whether FUNC will be
2444n/a called additionally to the other bound function or whether it will
2445n/a replace the previous function. See bind for the return value."""
2446n/a return self._bind((self._w, 'bind', tagOrId),
2447n/a sequence, func, add)
2448n/a def canvasx(self, screenx, gridspacing=None):
2449n/a """Return the canvas x coordinate of pixel position SCREENX rounded
2450n/a to nearest multiple of GRIDSPACING units."""
2451n/a return self.tk.getdouble(self.tk.call(
2452n/a self._w, 'canvasx', screenx, gridspacing))
2453n/a def canvasy(self, screeny, gridspacing=None):
2454n/a """Return the canvas y coordinate of pixel position SCREENY rounded
2455n/a to nearest multiple of GRIDSPACING units."""
2456n/a return self.tk.getdouble(self.tk.call(
2457n/a self._w, 'canvasy', screeny, gridspacing))
2458n/a def coords(self, *args):
2459n/a """Return a list of coordinates for the item given in ARGS."""
2460n/a # XXX Should use _flatten on args
2461n/a return [self.tk.getdouble(x) for x in
2462n/a self.tk.splitlist(
2463n/a self.tk.call((self._w, 'coords') + args))]
2464n/a def _create(self, itemType, args, kw): # Args: (val, val, ..., cnf={})
2465n/a """Internal function."""
2466n/a args = _flatten(args)
2467n/a cnf = args[-1]
2468n/a if isinstance(cnf, (dict, tuple)):
2469n/a args = args[:-1]
2470n/a else:
2471n/a cnf = {}
2472n/a return self.tk.getint(self.tk.call(
2473n/a self._w, 'create', itemType,
2474n/a *(args + self._options(cnf, kw))))
2475n/a def create_arc(self, *args, **kw):
2476n/a """Create arc shaped region with coordinates x1,y1,x2,y2."""
2477n/a return self._create('arc', args, kw)
2478n/a def create_bitmap(self, *args, **kw):
2479n/a """Create bitmap with coordinates x1,y1."""
2480n/a return self._create('bitmap', args, kw)
2481n/a def create_image(self, *args, **kw):
2482n/a """Create image item with coordinates x1,y1."""
2483n/a return self._create('image', args, kw)
2484n/a def create_line(self, *args, **kw):
2485n/a """Create line with coordinates x1,y1,...,xn,yn."""
2486n/a return self._create('line', args, kw)
2487n/a def create_oval(self, *args, **kw):
2488n/a """Create oval with coordinates x1,y1,x2,y2."""
2489n/a return self._create('oval', args, kw)
2490n/a def create_polygon(self, *args, **kw):
2491n/a """Create polygon with coordinates x1,y1,...,xn,yn."""
2492n/a return self._create('polygon', args, kw)
2493n/a def create_rectangle(self, *args, **kw):
2494n/a """Create rectangle with coordinates x1,y1,x2,y2."""
2495n/a return self._create('rectangle', args, kw)
2496n/a def create_text(self, *args, **kw):
2497n/a """Create text with coordinates x1,y1."""
2498n/a return self._create('text', args, kw)
2499n/a def create_window(self, *args, **kw):
2500n/a """Create window with coordinates x1,y1,x2,y2."""
2501n/a return self._create('window', args, kw)
2502n/a def dchars(self, *args):
2503n/a """Delete characters of text items identified by tag or id in ARGS (possibly
2504n/a several times) from FIRST to LAST character (including)."""
2505n/a self.tk.call((self._w, 'dchars') + args)
2506n/a def delete(self, *args):
2507n/a """Delete items identified by all tag or ids contained in ARGS."""
2508n/a self.tk.call((self._w, 'delete') + args)
2509n/a def dtag(self, *args):
2510n/a """Delete tag or id given as last arguments in ARGS from items
2511n/a identified by first argument in ARGS."""
2512n/a self.tk.call((self._w, 'dtag') + args)
2513n/a def find(self, *args):
2514n/a """Internal function."""
2515n/a return self._getints(
2516n/a self.tk.call((self._w, 'find') + args)) or ()
2517n/a def find_above(self, tagOrId):
2518n/a """Return items above TAGORID."""
2519n/a return self.find('above', tagOrId)
2520n/a def find_all(self):
2521n/a """Return all items."""
2522n/a return self.find('all')
2523n/a def find_below(self, tagOrId):
2524n/a """Return all items below TAGORID."""
2525n/a return self.find('below', tagOrId)
2526n/a def find_closest(self, x, y, halo=None, start=None):
2527n/a """Return item which is closest to pixel at X, Y.
2528n/a If several match take the top-most.
2529n/a All items closer than HALO are considered overlapping (all are
2530n/a closests). If START is specified the next below this tag is taken."""
2531n/a return self.find('closest', x, y, halo, start)
2532n/a def find_enclosed(self, x1, y1, x2, y2):
2533n/a """Return all items in rectangle defined
2534n/a by X1,Y1,X2,Y2."""
2535n/a return self.find('enclosed', x1, y1, x2, y2)
2536n/a def find_overlapping(self, x1, y1, x2, y2):
2537n/a """Return all items which overlap the rectangle
2538n/a defined by X1,Y1,X2,Y2."""
2539n/a return self.find('overlapping', x1, y1, x2, y2)
2540n/a def find_withtag(self, tagOrId):
2541n/a """Return all items with TAGORID."""
2542n/a return self.find('withtag', tagOrId)
2543n/a def focus(self, *args):
2544n/a """Set focus to the first item specified in ARGS."""
2545n/a return self.tk.call((self._w, 'focus') + args)
2546n/a def gettags(self, *args):
2547n/a """Return tags associated with the first item specified in ARGS."""
2548n/a return self.tk.splitlist(
2549n/a self.tk.call((self._w, 'gettags') + args))
2550n/a def icursor(self, *args):
2551n/a """Set cursor at position POS in the item identified by TAGORID.
2552n/a In ARGS TAGORID must be first."""
2553n/a self.tk.call((self._w, 'icursor') + args)
2554n/a def index(self, *args):
2555n/a """Return position of cursor as integer in item specified in ARGS."""
2556n/a return self.tk.getint(self.tk.call((self._w, 'index') + args))
2557n/a def insert(self, *args):
2558n/a """Insert TEXT in item TAGORID at position POS. ARGS must
2559n/a be TAGORID POS TEXT."""
2560n/a self.tk.call((self._w, 'insert') + args)
2561n/a def itemcget(self, tagOrId, option):
2562n/a """Return the resource value for an OPTION for item TAGORID."""
2563n/a return self.tk.call(
2564n/a (self._w, 'itemcget') + (tagOrId, '-'+option))
2565n/a def itemconfigure(self, tagOrId, cnf=None, **kw):
2566n/a """Configure resources of an item TAGORID.
2567n/a
2568n/a The values for resources are specified as keyword
2569n/a arguments. To get an overview about
2570n/a the allowed keyword arguments call the method without arguments.
2571n/a """
2572n/a return self._configure(('itemconfigure', tagOrId), cnf, kw)
2573n/a itemconfig = itemconfigure
2574n/a # lower, tkraise/lift hide Misc.lower, Misc.tkraise/lift,
2575n/a # so the preferred name for them is tag_lower, tag_raise
2576n/a # (similar to tag_bind, and similar to the Text widget);
2577n/a # unfortunately can't delete the old ones yet (maybe in 1.6)
2578n/a def tag_lower(self, *args):
2579n/a """Lower an item TAGORID given in ARGS
2580n/a (optional below another item)."""
2581n/a self.tk.call((self._w, 'lower') + args)
2582n/a lower = tag_lower
2583n/a def move(self, *args):
2584n/a """Move an item TAGORID given in ARGS."""
2585n/a self.tk.call((self._w, 'move') + args)
2586n/a def postscript(self, cnf={}, **kw):
2587n/a """Print the contents of the canvas to a postscript
2588n/a file. Valid options: colormap, colormode, file, fontmap,
2589n/a height, pageanchor, pageheight, pagewidth, pagex, pagey,
2590n/a rotate, witdh, x, y."""
2591n/a return self.tk.call((self._w, 'postscript') +
2592n/a self._options(cnf, kw))
2593n/a def tag_raise(self, *args):
2594n/a """Raise an item TAGORID given in ARGS
2595n/a (optional above another item)."""
2596n/a self.tk.call((self._w, 'raise') + args)
2597n/a lift = tkraise = tag_raise
2598n/a def scale(self, *args):
2599n/a """Scale item TAGORID with XORIGIN, YORIGIN, XSCALE, YSCALE."""
2600n/a self.tk.call((self._w, 'scale') + args)
2601n/a def scan_mark(self, x, y):
2602n/a """Remember the current X, Y coordinates."""
2603n/a self.tk.call(self._w, 'scan', 'mark', x, y)
2604n/a def scan_dragto(self, x, y, gain=10):
2605n/a """Adjust the view of the canvas to GAIN times the
2606n/a difference between X and Y and the coordinates given in
2607n/a scan_mark."""
2608n/a self.tk.call(self._w, 'scan', 'dragto', x, y, gain)
2609n/a def select_adjust(self, tagOrId, index):
2610n/a """Adjust the end of the selection near the cursor of an item TAGORID to index."""
2611n/a self.tk.call(self._w, 'select', 'adjust', tagOrId, index)
2612n/a def select_clear(self):
2613n/a """Clear the selection if it is in this widget."""
2614n/a self.tk.call(self._w, 'select', 'clear')
2615n/a def select_from(self, tagOrId, index):
2616n/a """Set the fixed end of a selection in item TAGORID to INDEX."""
2617n/a self.tk.call(self._w, 'select', 'from', tagOrId, index)
2618n/a def select_item(self):
2619n/a """Return the item which has the selection."""
2620n/a return self.tk.call(self._w, 'select', 'item') or None
2621n/a def select_to(self, tagOrId, index):
2622n/a """Set the variable end of a selection in item TAGORID to INDEX."""
2623n/a self.tk.call(self._w, 'select', 'to', tagOrId, index)
2624n/a def type(self, tagOrId):
2625n/a """Return the type of the item TAGORID."""
2626n/a return self.tk.call(self._w, 'type', tagOrId) or None
2627n/a
2628n/aclass Checkbutton(Widget):
2629n/a """Checkbutton widget which is either in on- or off-state."""
2630n/a def __init__(self, master=None, cnf={}, **kw):
2631n/a """Construct a checkbutton widget with the parent MASTER.
2632n/a
2633n/a Valid resource names: activebackground, activeforeground, anchor,
2634n/a background, bd, bg, bitmap, borderwidth, command, cursor,
2635n/a disabledforeground, fg, font, foreground, height,
2636n/a highlightbackground, highlightcolor, highlightthickness, image,
2637n/a indicatoron, justify, offvalue, onvalue, padx, pady, relief,
2638n/a selectcolor, selectimage, state, takefocus, text, textvariable,
2639n/a underline, variable, width, wraplength."""
2640n/a Widget.__init__(self, master, 'checkbutton', cnf, kw)
2641n/a def deselect(self):
2642n/a """Put the button in off-state."""
2643n/a self.tk.call(self._w, 'deselect')
2644n/a def flash(self):
2645n/a """Flash the button."""
2646n/a self.tk.call(self._w, 'flash')
2647n/a def invoke(self):
2648n/a """Toggle the button and invoke a command if given as resource."""
2649n/a return self.tk.call(self._w, 'invoke')
2650n/a def select(self):
2651n/a """Put the button in on-state."""
2652n/a self.tk.call(self._w, 'select')
2653n/a def toggle(self):
2654n/a """Toggle the button."""
2655n/a self.tk.call(self._w, 'toggle')
2656n/a
2657n/aclass Entry(Widget, XView):
2658n/a """Entry widget which allows displaying simple text."""
2659n/a def __init__(self, master=None, cnf={}, **kw):
2660n/a """Construct an entry widget with the parent MASTER.
2661n/a
2662n/a Valid resource names: background, bd, bg, borderwidth, cursor,
2663n/a exportselection, fg, font, foreground, highlightbackground,
2664n/a highlightcolor, highlightthickness, insertbackground,
2665n/a insertborderwidth, insertofftime, insertontime, insertwidth,
2666n/a invalidcommand, invcmd, justify, relief, selectbackground,
2667n/a selectborderwidth, selectforeground, show, state, takefocus,
2668n/a textvariable, validate, validatecommand, vcmd, width,
2669n/a xscrollcommand."""
2670n/a Widget.__init__(self, master, 'entry', cnf, kw)
2671n/a def delete(self, first, last=None):
2672n/a """Delete text from FIRST to LAST (not included)."""
2673n/a self.tk.call(self._w, 'delete', first, last)
2674n/a def get(self):
2675n/a """Return the text."""
2676n/a return self.tk.call(self._w, 'get')
2677n/a def icursor(self, index):
2678n/a """Insert cursor at INDEX."""
2679n/a self.tk.call(self._w, 'icursor', index)
2680n/a def index(self, index):
2681n/a """Return position of cursor."""
2682n/a return self.tk.getint(self.tk.call(
2683n/a self._w, 'index', index))
2684n/a def insert(self, index, string):
2685n/a """Insert STRING at INDEX."""
2686n/a self.tk.call(self._w, 'insert', index, string)
2687n/a def scan_mark(self, x):
2688n/a """Remember the current X, Y coordinates."""
2689n/a self.tk.call(self._w, 'scan', 'mark', x)
2690n/a def scan_dragto(self, x):
2691n/a """Adjust the view of the canvas to 10 times the
2692n/a difference between X and Y and the coordinates given in
2693n/a scan_mark."""
2694n/a self.tk.call(self._w, 'scan', 'dragto', x)
2695n/a def selection_adjust(self, index):
2696n/a """Adjust the end of the selection near the cursor to INDEX."""
2697n/a self.tk.call(self._w, 'selection', 'adjust', index)
2698n/a select_adjust = selection_adjust
2699n/a def selection_clear(self):
2700n/a """Clear the selection if it is in this widget."""
2701n/a self.tk.call(self._w, 'selection', 'clear')
2702n/a select_clear = selection_clear
2703n/a def selection_from(self, index):
2704n/a """Set the fixed end of a selection to INDEX."""
2705n/a self.tk.call(self._w, 'selection', 'from', index)
2706n/a select_from = selection_from
2707n/a def selection_present(self):
2708n/a """Return True if there are characters selected in the entry, False
2709n/a otherwise."""
2710n/a return self.tk.getboolean(
2711n/a self.tk.call(self._w, 'selection', 'present'))
2712n/a select_present = selection_present
2713n/a def selection_range(self, start, end):
2714n/a """Set the selection from START to END (not included)."""
2715n/a self.tk.call(self._w, 'selection', 'range', start, end)
2716n/a select_range = selection_range
2717n/a def selection_to(self, index):
2718n/a """Set the variable end of a selection to INDEX."""
2719n/a self.tk.call(self._w, 'selection', 'to', index)
2720n/a select_to = selection_to
2721n/a
2722n/aclass Frame(Widget):
2723n/a """Frame widget which may contain other widgets and can have a 3D border."""
2724n/a def __init__(self, master=None, cnf={}, **kw):
2725n/a """Construct a frame widget with the parent MASTER.
2726n/a
2727n/a Valid resource names: background, bd, bg, borderwidth, class,
2728n/a colormap, container, cursor, height, highlightbackground,
2729n/a highlightcolor, highlightthickness, relief, takefocus, visual, width."""
2730n/a cnf = _cnfmerge((cnf, kw))
2731n/a extra = ()
2732n/a if 'class_' in cnf:
2733n/a extra = ('-class', cnf['class_'])
2734n/a del cnf['class_']
2735n/a elif 'class' in cnf:
2736n/a extra = ('-class', cnf['class'])
2737n/a del cnf['class']
2738n/a Widget.__init__(self, master, 'frame', cnf, {}, extra)
2739n/a
2740n/aclass Label(Widget):
2741n/a """Label widget which can display text and bitmaps."""
2742n/a def __init__(self, master=None, cnf={}, **kw):
2743n/a """Construct a label widget with the parent MASTER.
2744n/a
2745n/a STANDARD OPTIONS
2746n/a
2747n/a activebackground, activeforeground, anchor,
2748n/a background, bitmap, borderwidth, cursor,
2749n/a disabledforeground, font, foreground,
2750n/a highlightbackground, highlightcolor,
2751n/a highlightthickness, image, justify,
2752n/a padx, pady, relief, takefocus, text,
2753n/a textvariable, underline, wraplength
2754n/a
2755n/a WIDGET-SPECIFIC OPTIONS
2756n/a
2757n/a height, state, width
2758n/a
2759n/a """
2760n/a Widget.__init__(self, master, 'label', cnf, kw)
2761n/a
2762n/aclass Listbox(Widget, XView, YView):
2763n/a """Listbox widget which can display a list of strings."""
2764n/a def __init__(self, master=None, cnf={}, **kw):
2765n/a """Construct a listbox widget with the parent MASTER.
2766n/a
2767n/a Valid resource names: background, bd, bg, borderwidth, cursor,
2768n/a exportselection, fg, font, foreground, height, highlightbackground,
2769n/a highlightcolor, highlightthickness, relief, selectbackground,
2770n/a selectborderwidth, selectforeground, selectmode, setgrid, takefocus,
2771n/a width, xscrollcommand, yscrollcommand, listvariable."""
2772n/a Widget.__init__(self, master, 'listbox', cnf, kw)
2773n/a def activate(self, index):
2774n/a """Activate item identified by INDEX."""
2775n/a self.tk.call(self._w, 'activate', index)
2776n/a def bbox(self, index):
2777n/a """Return a tuple of X1,Y1,X2,Y2 coordinates for a rectangle
2778n/a which encloses the item identified by the given index."""
2779n/a return self._getints(self.tk.call(self._w, 'bbox', index)) or None
2780n/a def curselection(self):
2781n/a """Return the indices of currently selected item."""
2782n/a return self._getints(self.tk.call(self._w, 'curselection')) or ()
2783n/a def delete(self, first, last=None):
2784n/a """Delete items from FIRST to LAST (included)."""
2785n/a self.tk.call(self._w, 'delete', first, last)
2786n/a def get(self, first, last=None):
2787n/a """Get list of items from FIRST to LAST (included)."""
2788n/a if last is not None:
2789n/a return self.tk.splitlist(self.tk.call(
2790n/a self._w, 'get', first, last))
2791n/a else:
2792n/a return self.tk.call(self._w, 'get', first)
2793n/a def index(self, index):
2794n/a """Return index of item identified with INDEX."""
2795n/a i = self.tk.call(self._w, 'index', index)
2796n/a if i == 'none': return None
2797n/a return self.tk.getint(i)
2798n/a def insert(self, index, *elements):
2799n/a """Insert ELEMENTS at INDEX."""
2800n/a self.tk.call((self._w, 'insert', index) + elements)
2801n/a def nearest(self, y):
2802n/a """Get index of item which is nearest to y coordinate Y."""
2803n/a return self.tk.getint(self.tk.call(
2804n/a self._w, 'nearest', y))
2805n/a def scan_mark(self, x, y):
2806n/a """Remember the current X, Y coordinates."""
2807n/a self.tk.call(self._w, 'scan', 'mark', x, y)
2808n/a def scan_dragto(self, x, y):
2809n/a """Adjust the view of the listbox to 10 times the
2810n/a difference between X and Y and the coordinates given in
2811n/a scan_mark."""
2812n/a self.tk.call(self._w, 'scan', 'dragto', x, y)
2813n/a def see(self, index):
2814n/a """Scroll such that INDEX is visible."""
2815n/a self.tk.call(self._w, 'see', index)
2816n/a def selection_anchor(self, index):
2817n/a """Set the fixed end oft the selection to INDEX."""
2818n/a self.tk.call(self._w, 'selection', 'anchor', index)
2819n/a select_anchor = selection_anchor
2820n/a def selection_clear(self, first, last=None):
2821n/a """Clear the selection from FIRST to LAST (included)."""
2822n/a self.tk.call(self._w,
2823n/a 'selection', 'clear', first, last)
2824n/a select_clear = selection_clear
2825n/a def selection_includes(self, index):
2826n/a """Return 1 if INDEX is part of the selection."""
2827n/a return self.tk.getboolean(self.tk.call(
2828n/a self._w, 'selection', 'includes', index))
2829n/a select_includes = selection_includes
2830n/a def selection_set(self, first, last=None):
2831n/a """Set the selection from FIRST to LAST (included) without
2832n/a changing the currently selected elements."""
2833n/a self.tk.call(self._w, 'selection', 'set', first, last)
2834n/a select_set = selection_set
2835n/a def size(self):
2836n/a """Return the number of elements in the listbox."""
2837n/a return self.tk.getint(self.tk.call(self._w, 'size'))
2838n/a def itemcget(self, index, option):
2839n/a """Return the resource value for an ITEM and an OPTION."""
2840n/a return self.tk.call(
2841n/a (self._w, 'itemcget') + (index, '-'+option))
2842n/a def itemconfigure(self, index, cnf=None, **kw):
2843n/a """Configure resources of an ITEM.
2844n/a
2845n/a The values for resources are specified as keyword arguments.
2846n/a To get an overview about the allowed keyword arguments
2847n/a call the method without arguments.
2848n/a Valid resource names: background, bg, foreground, fg,
2849n/a selectbackground, selectforeground."""
2850n/a return self._configure(('itemconfigure', index), cnf, kw)
2851n/a itemconfig = itemconfigure
2852n/a
2853n/aclass Menu(Widget):
2854n/a """Menu widget which allows displaying menu bars, pull-down menus and pop-up menus."""
2855n/a def __init__(self, master=None, cnf={}, **kw):
2856n/a """Construct menu widget with the parent MASTER.
2857n/a
2858n/a Valid resource names: activebackground, activeborderwidth,
2859n/a activeforeground, background, bd, bg, borderwidth, cursor,
2860n/a disabledforeground, fg, font, foreground, postcommand, relief,
2861n/a selectcolor, takefocus, tearoff, tearoffcommand, title, type."""
2862n/a Widget.__init__(self, master, 'menu', cnf, kw)
2863n/a def tk_popup(self, x, y, entry=""):
2864n/a """Post the menu at position X,Y with entry ENTRY."""
2865n/a self.tk.call('tk_popup', self._w, x, y, entry)
2866n/a def activate(self, index):
2867n/a """Activate entry at INDEX."""
2868n/a self.tk.call(self._w, 'activate', index)
2869n/a def add(self, itemType, cnf={}, **kw):
2870n/a """Internal function."""
2871n/a self.tk.call((self._w, 'add', itemType) +
2872n/a self._options(cnf, kw))
2873n/a def add_cascade(self, cnf={}, **kw):
2874n/a """Add hierarchical menu item."""
2875n/a self.add('cascade', cnf or kw)
2876n/a def add_checkbutton(self, cnf={}, **kw):
2877n/a """Add checkbutton menu item."""
2878n/a self.add('checkbutton', cnf or kw)
2879n/a def add_command(self, cnf={}, **kw):
2880n/a """Add command menu item."""
2881n/a self.add('command', cnf or kw)
2882n/a def add_radiobutton(self, cnf={}, **kw):
2883n/a """Addd radio menu item."""
2884n/a self.add('radiobutton', cnf or kw)
2885n/a def add_separator(self, cnf={}, **kw):
2886n/a """Add separator."""
2887n/a self.add('separator', cnf or kw)
2888n/a def insert(self, index, itemType, cnf={}, **kw):
2889n/a """Internal function."""
2890n/a self.tk.call((self._w, 'insert', index, itemType) +
2891n/a self._options(cnf, kw))
2892n/a def insert_cascade(self, index, cnf={}, **kw):
2893n/a """Add hierarchical menu item at INDEX."""
2894n/a self.insert(index, 'cascade', cnf or kw)
2895n/a def insert_checkbutton(self, index, cnf={}, **kw):
2896n/a """Add checkbutton menu item at INDEX."""
2897n/a self.insert(index, 'checkbutton', cnf or kw)
2898n/a def insert_command(self, index, cnf={}, **kw):
2899n/a """Add command menu item at INDEX."""
2900n/a self.insert(index, 'command', cnf or kw)
2901n/a def insert_radiobutton(self, index, cnf={}, **kw):
2902n/a """Addd radio menu item at INDEX."""
2903n/a self.insert(index, 'radiobutton', cnf or kw)
2904n/a def insert_separator(self, index, cnf={}, **kw):
2905n/a """Add separator at INDEX."""
2906n/a self.insert(index, 'separator', cnf or kw)
2907n/a def delete(self, index1, index2=None):
2908n/a """Delete menu items between INDEX1 and INDEX2 (included)."""
2909n/a if index2 is None:
2910n/a index2 = index1
2911n/a
2912n/a num_index1, num_index2 = self.index(index1), self.index(index2)
2913n/a if (num_index1 is None) or (num_index2 is None):
2914n/a num_index1, num_index2 = 0, -1
2915n/a
2916n/a for i in range(num_index1, num_index2 + 1):
2917n/a if 'command' in self.entryconfig(i):
2918n/a c = str(self.entrycget(i, 'command'))
2919n/a if c:
2920n/a self.deletecommand(c)
2921n/a self.tk.call(self._w, 'delete', index1, index2)
2922n/a def entrycget(self, index, option):
2923n/a """Return the resource value of a menu item for OPTION at INDEX."""
2924n/a return self.tk.call(self._w, 'entrycget', index, '-' + option)
2925n/a def entryconfigure(self, index, cnf=None, **kw):
2926n/a """Configure a menu item at INDEX."""
2927n/a return self._configure(('entryconfigure', index), cnf, kw)
2928n/a entryconfig = entryconfigure
2929n/a def index(self, index):
2930n/a """Return the index of a menu item identified by INDEX."""
2931n/a i = self.tk.call(self._w, 'index', index)
2932n/a if i == 'none': return None
2933n/a return self.tk.getint(i)
2934n/a def invoke(self, index):
2935n/a """Invoke a menu item identified by INDEX and execute
2936n/a the associated command."""
2937n/a return self.tk.call(self._w, 'invoke', index)
2938n/a def post(self, x, y):
2939n/a """Display a menu at position X,Y."""
2940n/a self.tk.call(self._w, 'post', x, y)
2941n/a def type(self, index):
2942n/a """Return the type of the menu item at INDEX."""
2943n/a return self.tk.call(self._w, 'type', index)
2944n/a def unpost(self):
2945n/a """Unmap a menu."""
2946n/a self.tk.call(self._w, 'unpost')
2947n/a def xposition(self, index): # new in Tk 8.5
2948n/a """Return the x-position of the leftmost pixel of the menu item
2949n/a at INDEX."""
2950n/a return self.tk.getint(self.tk.call(self._w, 'xposition', index))
2951n/a def yposition(self, index):
2952n/a """Return the y-position of the topmost pixel of the menu item at INDEX."""
2953n/a return self.tk.getint(self.tk.call(
2954n/a self._w, 'yposition', index))
2955n/a
2956n/aclass Menubutton(Widget):
2957n/a """Menubutton widget, obsolete since Tk8.0."""
2958n/a def __init__(self, master=None, cnf={}, **kw):
2959n/a Widget.__init__(self, master, 'menubutton', cnf, kw)
2960n/a
2961n/aclass Message(Widget):
2962n/a """Message widget to display multiline text. Obsolete since Label does it too."""
2963n/a def __init__(self, master=None, cnf={}, **kw):
2964n/a Widget.__init__(self, master, 'message', cnf, kw)
2965n/a
2966n/aclass Radiobutton(Widget):
2967n/a """Radiobutton widget which shows only one of several buttons in on-state."""
2968n/a def __init__(self, master=None, cnf={}, **kw):
2969n/a """Construct a radiobutton widget with the parent MASTER.
2970n/a
2971n/a Valid resource names: activebackground, activeforeground, anchor,
2972n/a background, bd, bg, bitmap, borderwidth, command, cursor,
2973n/a disabledforeground, fg, font, foreground, height,
2974n/a highlightbackground, highlightcolor, highlightthickness, image,
2975n/a indicatoron, justify, padx, pady, relief, selectcolor, selectimage,
2976n/a state, takefocus, text, textvariable, underline, value, variable,
2977n/a width, wraplength."""
2978n/a Widget.__init__(self, master, 'radiobutton', cnf, kw)
2979n/a def deselect(self):
2980n/a """Put the button in off-state."""
2981n/a
2982n/a self.tk.call(self._w, 'deselect')
2983n/a def flash(self):
2984n/a """Flash the button."""
2985n/a self.tk.call(self._w, 'flash')
2986n/a def invoke(self):
2987n/a """Toggle the button and invoke a command if given as resource."""
2988n/a return self.tk.call(self._w, 'invoke')
2989n/a def select(self):
2990n/a """Put the button in on-state."""
2991n/a self.tk.call(self._w, 'select')
2992n/a
2993n/aclass Scale(Widget):
2994n/a """Scale widget which can display a numerical scale."""
2995n/a def __init__(self, master=None, cnf={}, **kw):
2996n/a """Construct a scale widget with the parent MASTER.
2997n/a
2998n/a Valid resource names: activebackground, background, bigincrement, bd,
2999n/a bg, borderwidth, command, cursor, digits, fg, font, foreground, from,
3000n/a highlightbackground, highlightcolor, highlightthickness, label,
3001n/a length, orient, relief, repeatdelay, repeatinterval, resolution,
3002n/a showvalue, sliderlength, sliderrelief, state, takefocus,
3003n/a tickinterval, to, troughcolor, variable, width."""
3004n/a Widget.__init__(self, master, 'scale', cnf, kw)
3005n/a def get(self):
3006n/a """Get the current value as integer or float."""
3007n/a value = self.tk.call(self._w, 'get')
3008n/a try:
3009n/a return self.tk.getint(value)
3010n/a except (ValueError, TypeError, TclError):
3011n/a return self.tk.getdouble(value)
3012n/a def set(self, value):
3013n/a """Set the value to VALUE."""
3014n/a self.tk.call(self._w, 'set', value)
3015n/a def coords(self, value=None):
3016n/a """Return a tuple (X,Y) of the point along the centerline of the
3017n/a trough that corresponds to VALUE or the current value if None is
3018n/a given."""
3019n/a
3020n/a return self._getints(self.tk.call(self._w, 'coords', value))
3021n/a def identify(self, x, y):
3022n/a """Return where the point X,Y lies. Valid return values are "slider",
3023n/a "though1" and "though2"."""
3024n/a return self.tk.call(self._w, 'identify', x, y)
3025n/a
3026n/aclass Scrollbar(Widget):
3027n/a """Scrollbar widget which displays a slider at a certain position."""
3028n/a def __init__(self, master=None, cnf={}, **kw):
3029n/a """Construct a scrollbar widget with the parent MASTER.
3030n/a
3031n/a Valid resource names: activebackground, activerelief,
3032n/a background, bd, bg, borderwidth, command, cursor,
3033n/a elementborderwidth, highlightbackground,
3034n/a highlightcolor, highlightthickness, jump, orient,
3035n/a relief, repeatdelay, repeatinterval, takefocus,
3036n/a troughcolor, width."""
3037n/a Widget.__init__(self, master, 'scrollbar', cnf, kw)
3038n/a def activate(self, index=None):
3039n/a """Marks the element indicated by index as active.
3040n/a The only index values understood by this method are "arrow1",
3041n/a "slider", or "arrow2". If any other value is specified then no
3042n/a element of the scrollbar will be active. If index is not specified,
3043n/a the method returns the name of the element that is currently active,
3044n/a or None if no element is active."""
3045n/a return self.tk.call(self._w, 'activate', index) or None
3046n/a def delta(self, deltax, deltay):
3047n/a """Return the fractional change of the scrollbar setting if it
3048n/a would be moved by DELTAX or DELTAY pixels."""
3049n/a return self.tk.getdouble(
3050n/a self.tk.call(self._w, 'delta', deltax, deltay))
3051n/a def fraction(self, x, y):
3052n/a """Return the fractional value which corresponds to a slider
3053n/a position of X,Y."""
3054n/a return self.tk.getdouble(self.tk.call(self._w, 'fraction', x, y))
3055n/a def identify(self, x, y):
3056n/a """Return the element under position X,Y as one of
3057n/a "arrow1","slider","arrow2" or ""."""
3058n/a return self.tk.call(self._w, 'identify', x, y)
3059n/a def get(self):
3060n/a """Return the current fractional values (upper and lower end)
3061n/a of the slider position."""
3062n/a return self._getdoubles(self.tk.call(self._w, 'get'))
3063n/a def set(self, first, last):
3064n/a """Set the fractional values of the slider position (upper and
3065n/a lower ends as value between 0 and 1)."""
3066n/a self.tk.call(self._w, 'set', first, last)
3067n/a
3068n/a
3069n/a
3070n/aclass Text(Widget, XView, YView):
3071n/a """Text widget which can display text in various forms."""
3072n/a def __init__(self, master=None, cnf={}, **kw):
3073n/a """Construct a text widget with the parent MASTER.
3074n/a
3075n/a STANDARD OPTIONS
3076n/a
3077n/a background, borderwidth, cursor,
3078n/a exportselection, font, foreground,
3079n/a highlightbackground, highlightcolor,
3080n/a highlightthickness, insertbackground,
3081n/a insertborderwidth, insertofftime,
3082n/a insertontime, insertwidth, padx, pady,
3083n/a relief, selectbackground,
3084n/a selectborderwidth, selectforeground,
3085n/a setgrid, takefocus,
3086n/a xscrollcommand, yscrollcommand,
3087n/a
3088n/a WIDGET-SPECIFIC OPTIONS
3089n/a
3090n/a autoseparators, height, maxundo,
3091n/a spacing1, spacing2, spacing3,
3092n/a state, tabs, undo, width, wrap,
3093n/a
3094n/a """
3095n/a Widget.__init__(self, master, 'text', cnf, kw)
3096n/a def bbox(self, index):
3097n/a """Return a tuple of (x,y,width,height) which gives the bounding
3098n/a box of the visible part of the character at the given index."""
3099n/a return self._getints(
3100n/a self.tk.call(self._w, 'bbox', index)) or None
3101n/a def compare(self, index1, op, index2):
3102n/a """Return whether between index INDEX1 and index INDEX2 the
3103n/a relation OP is satisfied. OP is one of <, <=, ==, >=, >, or !=."""
3104n/a return self.tk.getboolean(self.tk.call(
3105n/a self._w, 'compare', index1, op, index2))
3106n/a def count(self, index1, index2, *args): # new in Tk 8.5
3107n/a """Counts the number of relevant things between the two indices.
3108n/a If index1 is after index2, the result will be a negative number
3109n/a (and this holds for each of the possible options).
3110n/a
3111n/a The actual items which are counted depends on the options given by
3112n/a args. The result is a list of integers, one for the result of each
3113n/a counting option given. Valid counting options are "chars",
3114n/a "displaychars", "displayindices", "displaylines", "indices",
3115n/a "lines", "xpixels" and "ypixels". There is an additional possible
3116n/a option "update", which if given then all subsequent options ensure
3117n/a that any possible out of date information is recalculated."""
3118n/a args = ['-%s' % arg for arg in args if not arg.startswith('-')]
3119n/a args += [index1, index2]
3120n/a res = self.tk.call(self._w, 'count', *args) or None
3121n/a if res is not None and len(args) <= 3:
3122n/a return (res, )
3123n/a else:
3124n/a return res
3125n/a def debug(self, boolean=None):
3126n/a """Turn on the internal consistency checks of the B-Tree inside the text
3127n/a widget according to BOOLEAN."""
3128n/a if boolean is None:
3129n/a return self.tk.getboolean(self.tk.call(self._w, 'debug'))
3130n/a self.tk.call(self._w, 'debug', boolean)
3131n/a def delete(self, index1, index2=None):
3132n/a """Delete the characters between INDEX1 and INDEX2 (not included)."""
3133n/a self.tk.call(self._w, 'delete', index1, index2)
3134n/a def dlineinfo(self, index):
3135n/a """Return tuple (x,y,width,height,baseline) giving the bounding box
3136n/a and baseline position of the visible part of the line containing
3137n/a the character at INDEX."""
3138n/a return self._getints(self.tk.call(self._w, 'dlineinfo', index))
3139n/a def dump(self, index1, index2=None, command=None, **kw):
3140n/a """Return the contents of the widget between index1 and index2.
3141n/a
3142n/a The type of contents returned in filtered based on the keyword
3143n/a parameters; if 'all', 'image', 'mark', 'tag', 'text', or 'window' are
3144n/a given and true, then the corresponding items are returned. The result
3145n/a is a list of triples of the form (key, value, index). If none of the
3146n/a keywords are true then 'all' is used by default.
3147n/a
3148n/a If the 'command' argument is given, it is called once for each element
3149n/a of the list of triples, with the values of each triple serving as the
3150n/a arguments to the function. In this case the list is not returned."""
3151n/a args = []
3152n/a func_name = None
3153n/a result = None
3154n/a if not command:
3155n/a # Never call the dump command without the -command flag, since the
3156n/a # output could involve Tcl quoting and would be a pain to parse
3157n/a # right. Instead just set the command to build a list of triples
3158n/a # as if we had done the parsing.
3159n/a result = []
3160n/a def append_triple(key, value, index, result=result):
3161n/a result.append((key, value, index))
3162n/a command = append_triple
3163n/a try:
3164n/a if not isinstance(command, str):
3165n/a func_name = command = self._register(command)
3166n/a args += ["-command", command]
3167n/a for key in kw:
3168n/a if kw[key]: args.append("-" + key)
3169n/a args.append(index1)
3170n/a if index2:
3171n/a args.append(index2)
3172n/a self.tk.call(self._w, "dump", *args)
3173n/a return result
3174n/a finally:
3175n/a if func_name:
3176n/a self.deletecommand(func_name)
3177n/a
3178n/a ## new in tk8.4
3179n/a def edit(self, *args):
3180n/a """Internal method
3181n/a
3182n/a This method controls the undo mechanism and
3183n/a the modified flag. The exact behavior of the
3184n/a command depends on the option argument that
3185n/a follows the edit argument. The following forms
3186n/a of the command are currently supported:
3187n/a
3188n/a edit_modified, edit_redo, edit_reset, edit_separator
3189n/a and edit_undo
3190n/a
3191n/a """
3192n/a return self.tk.call(self._w, 'edit', *args)
3193n/a
3194n/a def edit_modified(self, arg=None):
3195n/a """Get or Set the modified flag
3196n/a
3197n/a If arg is not specified, returns the modified
3198n/a flag of the widget. The insert, delete, edit undo and
3199n/a edit redo commands or the user can set or clear the
3200n/a modified flag. If boolean is specified, sets the
3201n/a modified flag of the widget to arg.
3202n/a """
3203n/a return self.edit("modified", arg)
3204n/a
3205n/a def edit_redo(self):
3206n/a """Redo the last undone edit
3207n/a
3208n/a When the undo option is true, reapplies the last
3209n/a undone edits provided no other edits were done since
3210n/a then. Generates an error when the redo stack is empty.
3211n/a Does nothing when the undo option is false.
3212n/a """
3213n/a return self.edit("redo")
3214n/a
3215n/a def edit_reset(self):
3216n/a """Clears the undo and redo stacks
3217n/a """
3218n/a return self.edit("reset")
3219n/a
3220n/a def edit_separator(self):
3221n/a """Inserts a separator (boundary) on the undo stack.
3222n/a
3223n/a Does nothing when the undo option is false
3224n/a """
3225n/a return self.edit("separator")
3226n/a
3227n/a def edit_undo(self):
3228n/a """Undoes the last edit action
3229n/a
3230n/a If the undo option is true. An edit action is defined
3231n/a as all the insert and delete commands that are recorded
3232n/a on the undo stack in between two separators. Generates
3233n/a an error when the undo stack is empty. Does nothing
3234n/a when the undo option is false
3235n/a """
3236n/a return self.edit("undo")
3237n/a
3238n/a def get(self, index1, index2=None):
3239n/a """Return the text from INDEX1 to INDEX2 (not included)."""
3240n/a return self.tk.call(self._w, 'get', index1, index2)
3241n/a # (Image commands are new in 8.0)
3242n/a def image_cget(self, index, option):
3243n/a """Return the value of OPTION of an embedded image at INDEX."""
3244n/a if option[:1] != "-":
3245n/a option = "-" + option
3246n/a if option[-1:] == "_":
3247n/a option = option[:-1]
3248n/a return self.tk.call(self._w, "image", "cget", index, option)
3249n/a def image_configure(self, index, cnf=None, **kw):
3250n/a """Configure an embedded image at INDEX."""
3251n/a return self._configure(('image', 'configure', index), cnf, kw)
3252n/a def image_create(self, index, cnf={}, **kw):
3253n/a """Create an embedded image at INDEX."""
3254n/a return self.tk.call(
3255n/a self._w, "image", "create", index,
3256n/a *self._options(cnf, kw))
3257n/a def image_names(self):
3258n/a """Return all names of embedded images in this widget."""
3259n/a return self.tk.call(self._w, "image", "names")
3260n/a def index(self, index):
3261n/a """Return the index in the form line.char for INDEX."""
3262n/a return str(self.tk.call(self._w, 'index', index))
3263n/a def insert(self, index, chars, *args):
3264n/a """Insert CHARS before the characters at INDEX. An additional
3265n/a tag can be given in ARGS. Additional CHARS and tags can follow in ARGS."""
3266n/a self.tk.call((self._w, 'insert', index, chars) + args)
3267n/a def mark_gravity(self, markName, direction=None):
3268n/a """Change the gravity of a mark MARKNAME to DIRECTION (LEFT or RIGHT).
3269n/a Return the current value if None is given for DIRECTION."""
3270n/a return self.tk.call(
3271n/a (self._w, 'mark', 'gravity', markName, direction))
3272n/a def mark_names(self):
3273n/a """Return all mark names."""
3274n/a return self.tk.splitlist(self.tk.call(
3275n/a self._w, 'mark', 'names'))
3276n/a def mark_set(self, markName, index):
3277n/a """Set mark MARKNAME before the character at INDEX."""
3278n/a self.tk.call(self._w, 'mark', 'set', markName, index)
3279n/a def mark_unset(self, *markNames):
3280n/a """Delete all marks in MARKNAMES."""
3281n/a self.tk.call((self._w, 'mark', 'unset') + markNames)
3282n/a def mark_next(self, index):
3283n/a """Return the name of the next mark after INDEX."""
3284n/a return self.tk.call(self._w, 'mark', 'next', index) or None
3285n/a def mark_previous(self, index):
3286n/a """Return the name of the previous mark before INDEX."""
3287n/a return self.tk.call(self._w, 'mark', 'previous', index) or None
3288n/a def peer_create(self, newPathName, cnf={}, **kw): # new in Tk 8.5
3289n/a """Creates a peer text widget with the given newPathName, and any
3290n/a optional standard configuration options. By default the peer will
3291n/a have the same start and end line as the parent widget, but
3292n/a these can be overridden with the standard configuration options."""
3293n/a self.tk.call(self._w, 'peer', 'create', newPathName,
3294n/a *self._options(cnf, kw))
3295n/a def peer_names(self): # new in Tk 8.5
3296n/a """Returns a list of peers of this widget (this does not include
3297n/a the widget itself)."""
3298n/a return self.tk.splitlist(self.tk.call(self._w, 'peer', 'names'))
3299n/a def replace(self, index1, index2, chars, *args): # new in Tk 8.5
3300n/a """Replaces the range of characters between index1 and index2 with
3301n/a the given characters and tags specified by args.
3302n/a
3303n/a See the method insert for some more information about args, and the
3304n/a method delete for information about the indices."""
3305n/a self.tk.call(self._w, 'replace', index1, index2, chars, *args)
3306n/a def scan_mark(self, x, y):
3307n/a """Remember the current X, Y coordinates."""
3308n/a self.tk.call(self._w, 'scan', 'mark', x, y)
3309n/a def scan_dragto(self, x, y):
3310n/a """Adjust the view of the text to 10 times the
3311n/a difference between X and Y and the coordinates given in
3312n/a scan_mark."""
3313n/a self.tk.call(self._w, 'scan', 'dragto', x, y)
3314n/a def search(self, pattern, index, stopindex=None,
3315n/a forwards=None, backwards=None, exact=None,
3316n/a regexp=None, nocase=None, count=None, elide=None):
3317n/a """Search PATTERN beginning from INDEX until STOPINDEX.
3318n/a Return the index of the first character of a match or an
3319n/a empty string."""
3320n/a args = [self._w, 'search']
3321n/a if forwards: args.append('-forwards')
3322n/a if backwards: args.append('-backwards')
3323n/a if exact: args.append('-exact')
3324n/a if regexp: args.append('-regexp')
3325n/a if nocase: args.append('-nocase')
3326n/a if elide: args.append('-elide')
3327n/a if count: args.append('-count'); args.append(count)
3328n/a if pattern and pattern[0] == '-': args.append('--')
3329n/a args.append(pattern)
3330n/a args.append(index)
3331n/a if stopindex: args.append(stopindex)
3332n/a return str(self.tk.call(tuple(args)))
3333n/a def see(self, index):
3334n/a """Scroll such that the character at INDEX is visible."""
3335n/a self.tk.call(self._w, 'see', index)
3336n/a def tag_add(self, tagName, index1, *args):
3337n/a """Add tag TAGNAME to all characters between INDEX1 and index2 in ARGS.
3338n/a Additional pairs of indices may follow in ARGS."""
3339n/a self.tk.call(
3340n/a (self._w, 'tag', 'add', tagName, index1) + args)
3341n/a def tag_unbind(self, tagName, sequence, funcid=None):
3342n/a """Unbind for all characters with TAGNAME for event SEQUENCE the
3343n/a function identified with FUNCID."""
3344n/a self.tk.call(self._w, 'tag', 'bind', tagName, sequence, '')
3345n/a if funcid:
3346n/a self.deletecommand(funcid)
3347n/a def tag_bind(self, tagName, sequence, func, add=None):
3348n/a """Bind to all characters with TAGNAME at event SEQUENCE a call to function FUNC.
3349n/a
3350n/a An additional boolean parameter ADD specifies whether FUNC will be
3351n/a called additionally to the other bound function or whether it will
3352n/a replace the previous function. See bind for the return value."""
3353n/a return self._bind((self._w, 'tag', 'bind', tagName),
3354n/a sequence, func, add)
3355n/a def tag_cget(self, tagName, option):
3356n/a """Return the value of OPTION for tag TAGNAME."""
3357n/a if option[:1] != '-':
3358n/a option = '-' + option
3359n/a if option[-1:] == '_':
3360n/a option = option[:-1]
3361n/a return self.tk.call(self._w, 'tag', 'cget', tagName, option)
3362n/a def tag_configure(self, tagName, cnf=None, **kw):
3363n/a """Configure a tag TAGNAME."""
3364n/a return self._configure(('tag', 'configure', tagName), cnf, kw)
3365n/a tag_config = tag_configure
3366n/a def tag_delete(self, *tagNames):
3367n/a """Delete all tags in TAGNAMES."""
3368n/a self.tk.call((self._w, 'tag', 'delete') + tagNames)
3369n/a def tag_lower(self, tagName, belowThis=None):
3370n/a """Change the priority of tag TAGNAME such that it is lower
3371n/a than the priority of BELOWTHIS."""
3372n/a self.tk.call(self._w, 'tag', 'lower', tagName, belowThis)
3373n/a def tag_names(self, index=None):
3374n/a """Return a list of all tag names."""
3375n/a return self.tk.splitlist(
3376n/a self.tk.call(self._w, 'tag', 'names', index))
3377n/a def tag_nextrange(self, tagName, index1, index2=None):
3378n/a """Return a list of start and end index for the first sequence of
3379n/a characters between INDEX1 and INDEX2 which all have tag TAGNAME.
3380n/a The text is searched forward from INDEX1."""
3381n/a return self.tk.splitlist(self.tk.call(
3382n/a self._w, 'tag', 'nextrange', tagName, index1, index2))
3383n/a def tag_prevrange(self, tagName, index1, index2=None):
3384n/a """Return a list of start and end index for the first sequence of
3385n/a characters between INDEX1 and INDEX2 which all have tag TAGNAME.
3386n/a The text is searched backwards from INDEX1."""
3387n/a return self.tk.splitlist(self.tk.call(
3388n/a self._w, 'tag', 'prevrange', tagName, index1, index2))
3389n/a def tag_raise(self, tagName, aboveThis=None):
3390n/a """Change the priority of tag TAGNAME such that it is higher
3391n/a than the priority of ABOVETHIS."""
3392n/a self.tk.call(
3393n/a self._w, 'tag', 'raise', tagName, aboveThis)
3394n/a def tag_ranges(self, tagName):
3395n/a """Return a list of ranges of text which have tag TAGNAME."""
3396n/a return self.tk.splitlist(self.tk.call(
3397n/a self._w, 'tag', 'ranges', tagName))
3398n/a def tag_remove(self, tagName, index1, index2=None):
3399n/a """Remove tag TAGNAME from all characters between INDEX1 and INDEX2."""
3400n/a self.tk.call(
3401n/a self._w, 'tag', 'remove', tagName, index1, index2)
3402n/a def window_cget(self, index, option):
3403n/a """Return the value of OPTION of an embedded window at INDEX."""
3404n/a if option[:1] != '-':
3405n/a option = '-' + option
3406n/a if option[-1:] == '_':
3407n/a option = option[:-1]
3408n/a return self.tk.call(self._w, 'window', 'cget', index, option)
3409n/a def window_configure(self, index, cnf=None, **kw):
3410n/a """Configure an embedded window at INDEX."""
3411n/a return self._configure(('window', 'configure', index), cnf, kw)
3412n/a window_config = window_configure
3413n/a def window_create(self, index, cnf={}, **kw):
3414n/a """Create a window at INDEX."""
3415n/a self.tk.call(
3416n/a (self._w, 'window', 'create', index)
3417n/a + self._options(cnf, kw))
3418n/a def window_names(self):
3419n/a """Return all names of embedded windows in this widget."""
3420n/a return self.tk.splitlist(
3421n/a self.tk.call(self._w, 'window', 'names'))
3422n/a def yview_pickplace(self, *what):
3423n/a """Obsolete function, use see."""
3424n/a self.tk.call((self._w, 'yview', '-pickplace') + what)
3425n/a
3426n/a
3427n/aclass _setit:
3428n/a """Internal class. It wraps the command in the widget OptionMenu."""
3429n/a def __init__(self, var, value, callback=None):
3430n/a self.__value = value
3431n/a self.__var = var
3432n/a self.__callback = callback
3433n/a def __call__(self, *args):
3434n/a self.__var.set(self.__value)
3435n/a if self.__callback:
3436n/a self.__callback(self.__value, *args)
3437n/a
3438n/aclass OptionMenu(Menubutton):
3439n/a """OptionMenu which allows the user to select a value from a menu."""
3440n/a def __init__(self, master, variable, value, *values, **kwargs):
3441n/a """Construct an optionmenu widget with the parent MASTER, with
3442n/a the resource textvariable set to VARIABLE, the initially selected
3443n/a value VALUE, the other menu values VALUES and an additional
3444n/a keyword argument command."""
3445n/a kw = {"borderwidth": 2, "textvariable": variable,
3446n/a "indicatoron": 1, "relief": RAISED, "anchor": "c",
3447n/a "highlightthickness": 2}
3448n/a Widget.__init__(self, master, "menubutton", kw)
3449n/a self.widgetName = 'tk_optionMenu'
3450n/a menu = self.__menu = Menu(self, name="menu", tearoff=0)
3451n/a self.menuname = menu._w
3452n/a # 'command' is the only supported keyword
3453n/a callback = kwargs.get('command')
3454n/a if 'command' in kwargs:
3455n/a del kwargs['command']
3456n/a if kwargs:
3457n/a raise TclError('unknown option -'+kwargs.keys()[0])
3458n/a menu.add_command(label=value,
3459n/a command=_setit(variable, value, callback))
3460n/a for v in values:
3461n/a menu.add_command(label=v,
3462n/a command=_setit(variable, v, callback))
3463n/a self["menu"] = menu
3464n/a
3465n/a def __getitem__(self, name):
3466n/a if name == 'menu':
3467n/a return self.__menu
3468n/a return Widget.__getitem__(self, name)
3469n/a
3470n/a def destroy(self):
3471n/a """Destroy this widget and the associated menu."""
3472n/a Menubutton.destroy(self)
3473n/a self.__menu = None
3474n/a
3475n/aclass Image:
3476n/a """Base class for images."""
3477n/a _last_id = 0
3478n/a def __init__(self, imgtype, name=None, cnf={}, master=None, **kw):
3479n/a self.name = None
3480n/a if not master:
3481n/a master = _default_root
3482n/a if not master:
3483n/a raise RuntimeError('Too early to create image')
3484n/a self.tk = getattr(master, 'tk', master)
3485n/a if not name:
3486n/a Image._last_id += 1
3487n/a name = "pyimage%r" % (Image._last_id,) # tk itself would use image<x>
3488n/a if kw and cnf: cnf = _cnfmerge((cnf, kw))
3489n/a elif kw: cnf = kw
3490n/a options = ()
3491n/a for k, v in cnf.items():
3492n/a if callable(v):
3493n/a v = self._register(v)
3494n/a options = options + ('-'+k, v)
3495n/a self.tk.call(('image', 'create', imgtype, name,) + options)
3496n/a self.name = name
3497n/a def __str__(self): return self.name
3498n/a def __del__(self):
3499n/a if self.name:
3500n/a try:
3501n/a self.tk.call('image', 'delete', self.name)
3502n/a except TclError:
3503n/a # May happen if the root was destroyed
3504n/a pass
3505n/a def __setitem__(self, key, value):
3506n/a self.tk.call(self.name, 'configure', '-'+key, value)
3507n/a def __getitem__(self, key):
3508n/a return self.tk.call(self.name, 'configure', '-'+key)
3509n/a def configure(self, **kw):
3510n/a """Configure the image."""
3511n/a res = ()
3512n/a for k, v in _cnfmerge(kw).items():
3513n/a if v is not None:
3514n/a if k[-1] == '_': k = k[:-1]
3515n/a if callable(v):
3516n/a v = self._register(v)
3517n/a res = res + ('-'+k, v)
3518n/a self.tk.call((self.name, 'config') + res)
3519n/a config = configure
3520n/a def height(self):
3521n/a """Return the height of the image."""
3522n/a return self.tk.getint(
3523n/a self.tk.call('image', 'height', self.name))
3524n/a def type(self):
3525n/a """Return the type of the imgage, e.g. "photo" or "bitmap"."""
3526n/a return self.tk.call('image', 'type', self.name)
3527n/a def width(self):
3528n/a """Return the width of the image."""
3529n/a return self.tk.getint(
3530n/a self.tk.call('image', 'width', self.name))
3531n/a
3532n/aclass PhotoImage(Image):
3533n/a """Widget which can display colored images in GIF, PPM/PGM format."""
3534n/a def __init__(self, name=None, cnf={}, master=None, **kw):
3535n/a """Create an image with NAME.
3536n/a
3537n/a Valid resource names: data, format, file, gamma, height, palette,
3538n/a width."""
3539n/a Image.__init__(self, 'photo', name, cnf, master, **kw)
3540n/a def blank(self):
3541n/a """Display a transparent image."""
3542n/a self.tk.call(self.name, 'blank')
3543n/a def cget(self, option):
3544n/a """Return the value of OPTION."""
3545n/a return self.tk.call(self.name, 'cget', '-' + option)
3546n/a # XXX config
3547n/a def __getitem__(self, key):
3548n/a return self.tk.call(self.name, 'cget', '-' + key)
3549n/a # XXX copy -from, -to, ...?
3550n/a def copy(self):
3551n/a """Return a new PhotoImage with the same image as this widget."""
3552n/a destImage = PhotoImage(master=self.tk)
3553n/a self.tk.call(destImage, 'copy', self.name)
3554n/a return destImage
3555n/a def zoom(self, x, y=''):
3556n/a """Return a new PhotoImage with the same image as this widget
3557n/a but zoom it with a factor of x in the X direction and y in the Y
3558n/a direction. If y is not given, the default value is the same as x.
3559n/a """
3560n/a destImage = PhotoImage(master=self.tk)
3561n/a if y=='': y=x
3562n/a self.tk.call(destImage, 'copy', self.name, '-zoom',x,y)
3563n/a return destImage
3564n/a def subsample(self, x, y=''):
3565n/a """Return a new PhotoImage based on the same image as this widget
3566n/a but use only every Xth or Yth pixel. If y is not given, the
3567n/a default value is the same as x.
3568n/a """
3569n/a destImage = PhotoImage(master=self.tk)
3570n/a if y=='': y=x
3571n/a self.tk.call(destImage, 'copy', self.name, '-subsample',x,y)
3572n/a return destImage
3573n/a def get(self, x, y):
3574n/a """Return the color (red, green, blue) of the pixel at X,Y."""
3575n/a return self.tk.call(self.name, 'get', x, y)
3576n/a def put(self, data, to=None):
3577n/a """Put row formatted colors to image starting from
3578n/a position TO, e.g. image.put("{red green} {blue yellow}", to=(4,6))"""
3579n/a args = (self.name, 'put', data)
3580n/a if to:
3581n/a if to[0] == '-to':
3582n/a to = to[1:]
3583n/a args = args + ('-to',) + tuple(to)
3584n/a self.tk.call(args)
3585n/a # XXX read
3586n/a def write(self, filename, format=None, from_coords=None):
3587n/a """Write image to file FILENAME in FORMAT starting from
3588n/a position FROM_COORDS."""
3589n/a args = (self.name, 'write', filename)
3590n/a if format:
3591n/a args = args + ('-format', format)
3592n/a if from_coords:
3593n/a args = args + ('-from',) + tuple(from_coords)
3594n/a self.tk.call(args)
3595n/a
3596n/aclass BitmapImage(Image):
3597n/a """Widget which can display a bitmap."""
3598n/a def __init__(self, name=None, cnf={}, master=None, **kw):
3599n/a """Create a bitmap with NAME.
3600n/a
3601n/a Valid resource names: background, data, file, foreground, maskdata, maskfile."""
3602n/a Image.__init__(self, 'bitmap', name, cnf, master, **kw)
3603n/a
3604n/adef image_names():
3605n/a return _default_root.tk.splitlist(_default_root.tk.call('image', 'names'))
3606n/a
3607n/adef image_types():
3608n/a return _default_root.tk.splitlist(_default_root.tk.call('image', 'types'))
3609n/a
3610n/a
3611n/aclass Spinbox(Widget, XView):
3612n/a """spinbox widget."""
3613n/a def __init__(self, master=None, cnf={}, **kw):
3614n/a """Construct a spinbox widget with the parent MASTER.
3615n/a
3616n/a STANDARD OPTIONS
3617n/a
3618n/a activebackground, background, borderwidth,
3619n/a cursor, exportselection, font, foreground,
3620n/a highlightbackground, highlightcolor,
3621n/a highlightthickness, insertbackground,
3622n/a insertborderwidth, insertofftime,
3623n/a insertontime, insertwidth, justify, relief,
3624n/a repeatdelay, repeatinterval,
3625n/a selectbackground, selectborderwidth
3626n/a selectforeground, takefocus, textvariable
3627n/a xscrollcommand.
3628n/a
3629n/a WIDGET-SPECIFIC OPTIONS
3630n/a
3631n/a buttonbackground, buttoncursor,
3632n/a buttondownrelief, buttonuprelief,
3633n/a command, disabledbackground,
3634n/a disabledforeground, format, from,
3635n/a invalidcommand, increment,
3636n/a readonlybackground, state, to,
3637n/a validate, validatecommand values,
3638n/a width, wrap,
3639n/a """
3640n/a Widget.__init__(self, master, 'spinbox', cnf, kw)
3641n/a
3642n/a def bbox(self, index):
3643n/a """Return a tuple of X1,Y1,X2,Y2 coordinates for a
3644n/a rectangle which encloses the character given by index.
3645n/a
3646n/a The first two elements of the list give the x and y
3647n/a coordinates of the upper-left corner of the screen
3648n/a area covered by the character (in pixels relative
3649n/a to the widget) and the last two elements give the
3650n/a width and height of the character, in pixels. The
3651n/a bounding box may refer to a region outside the
3652n/a visible area of the window.
3653n/a """
3654n/a return self._getints(self.tk.call(self._w, 'bbox', index)) or None
3655n/a
3656n/a def delete(self, first, last=None):
3657n/a """Delete one or more elements of the spinbox.
3658n/a
3659n/a First is the index of the first character to delete,
3660n/a and last is the index of the character just after
3661n/a the last one to delete. If last isn't specified it
3662n/a defaults to first+1, i.e. a single character is
3663n/a deleted. This command returns an empty string.
3664n/a """
3665n/a return self.tk.call(self._w, 'delete', first, last)
3666n/a
3667n/a def get(self):
3668n/a """Returns the spinbox's string"""
3669n/a return self.tk.call(self._w, 'get')
3670n/a
3671n/a def icursor(self, index):
3672n/a """Alter the position of the insertion cursor.
3673n/a
3674n/a The insertion cursor will be displayed just before
3675n/a the character given by index. Returns an empty string
3676n/a """
3677n/a return self.tk.call(self._w, 'icursor', index)
3678n/a
3679n/a def identify(self, x, y):
3680n/a """Returns the name of the widget at position x, y
3681n/a
3682n/a Return value is one of: none, buttondown, buttonup, entry
3683n/a """
3684n/a return self.tk.call(self._w, 'identify', x, y)
3685n/a
3686n/a def index(self, index):
3687n/a """Returns the numerical index corresponding to index
3688n/a """
3689n/a return self.tk.call(self._w, 'index', index)
3690n/a
3691n/a def insert(self, index, s):
3692n/a """Insert string s at index
3693n/a
3694n/a Returns an empty string.
3695n/a """
3696n/a return self.tk.call(self._w, 'insert', index, s)
3697n/a
3698n/a def invoke(self, element):
3699n/a """Causes the specified element to be invoked
3700n/a
3701n/a The element could be buttondown or buttonup
3702n/a triggering the action associated with it.
3703n/a """
3704n/a return self.tk.call(self._w, 'invoke', element)
3705n/a
3706n/a def scan(self, *args):
3707n/a """Internal function."""
3708n/a return self._getints(
3709n/a self.tk.call((self._w, 'scan') + args)) or ()
3710n/a
3711n/a def scan_mark(self, x):
3712n/a """Records x and the current view in the spinbox window;
3713n/a
3714n/a used in conjunction with later scan dragto commands.
3715n/a Typically this command is associated with a mouse button
3716n/a press in the widget. It returns an empty string.
3717n/a """
3718n/a return self.scan("mark", x)
3719n/a
3720n/a def scan_dragto(self, x):
3721n/a """Compute the difference between the given x argument
3722n/a and the x argument to the last scan mark command
3723n/a
3724n/a It then adjusts the view left or right by 10 times the
3725n/a difference in x-coordinates. This command is typically
3726n/a associated with mouse motion events in the widget, to
3727n/a produce the effect of dragging the spinbox at high speed
3728n/a through the window. The return value is an empty string.
3729n/a """
3730n/a return self.scan("dragto", x)
3731n/a
3732n/a def selection(self, *args):
3733n/a """Internal function."""
3734n/a return self._getints(
3735n/a self.tk.call((self._w, 'selection') + args)) or ()
3736n/a
3737n/a def selection_adjust(self, index):
3738n/a """Locate the end of the selection nearest to the character
3739n/a given by index,
3740n/a
3741n/a Then adjust that end of the selection to be at index
3742n/a (i.e including but not going beyond index). The other
3743n/a end of the selection is made the anchor point for future
3744n/a select to commands. If the selection isn't currently in
3745n/a the spinbox, then a new selection is created to include
3746n/a the characters between index and the most recent selection
3747n/a anchor point, inclusive. Returns an empty string.
3748n/a """
3749n/a return self.selection("adjust", index)
3750n/a
3751n/a def selection_clear(self):
3752n/a """Clear the selection
3753n/a
3754n/a If the selection isn't in this widget then the
3755n/a command has no effect. Returns an empty string.
3756n/a """
3757n/a return self.selection("clear")
3758n/a
3759n/a def selection_element(self, element=None):
3760n/a """Sets or gets the currently selected element.
3761n/a
3762n/a If a spinbutton element is specified, it will be
3763n/a displayed depressed
3764n/a """
3765n/a return self.selection("element", element)
3766n/a
3767n/a###########################################################################
3768n/a
3769n/aclass LabelFrame(Widget):
3770n/a """labelframe widget."""
3771n/a def __init__(self, master=None, cnf={}, **kw):
3772n/a """Construct a labelframe widget with the parent MASTER.
3773n/a
3774n/a STANDARD OPTIONS
3775n/a
3776n/a borderwidth, cursor, font, foreground,
3777n/a highlightbackground, highlightcolor,
3778n/a highlightthickness, padx, pady, relief,
3779n/a takefocus, text
3780n/a
3781n/a WIDGET-SPECIFIC OPTIONS
3782n/a
3783n/a background, class, colormap, container,
3784n/a height, labelanchor, labelwidget,
3785n/a visual, width
3786n/a """
3787n/a Widget.__init__(self, master, 'labelframe', cnf, kw)
3788n/a
3789n/a########################################################################
3790n/a
3791n/aclass PanedWindow(Widget):
3792n/a """panedwindow widget."""
3793n/a def __init__(self, master=None, cnf={}, **kw):
3794n/a """Construct a panedwindow widget with the parent MASTER.
3795n/a
3796n/a STANDARD OPTIONS
3797n/a
3798n/a background, borderwidth, cursor, height,
3799n/a orient, relief, width
3800n/a
3801n/a WIDGET-SPECIFIC OPTIONS
3802n/a
3803n/a handlepad, handlesize, opaqueresize,
3804n/a sashcursor, sashpad, sashrelief,
3805n/a sashwidth, showhandle,
3806n/a """
3807n/a Widget.__init__(self, master, 'panedwindow', cnf, kw)
3808n/a
3809n/a def add(self, child, **kw):
3810n/a """Add a child widget to the panedwindow in a new pane.
3811n/a
3812n/a The child argument is the name of the child widget
3813n/a followed by pairs of arguments that specify how to
3814n/a manage the windows. The possible options and values
3815n/a are the ones accepted by the paneconfigure method.
3816n/a """
3817n/a self.tk.call((self._w, 'add', child) + self._options(kw))
3818n/a
3819n/a def remove(self, child):
3820n/a """Remove the pane containing child from the panedwindow
3821n/a
3822n/a All geometry management options for child will be forgotten.
3823n/a """
3824n/a self.tk.call(self._w, 'forget', child)
3825n/a forget=remove
3826n/a
3827n/a def identify(self, x, y):
3828n/a """Identify the panedwindow component at point x, y
3829n/a
3830n/a If the point is over a sash or a sash handle, the result
3831n/a is a two element list containing the index of the sash or
3832n/a handle, and a word indicating whether it is over a sash
3833n/a or a handle, such as {0 sash} or {2 handle}. If the point
3834n/a is over any other part of the panedwindow, the result is
3835n/a an empty list.
3836n/a """
3837n/a return self.tk.call(self._w, 'identify', x, y)
3838n/a
3839n/a def proxy(self, *args):
3840n/a """Internal function."""
3841n/a return self._getints(
3842n/a self.tk.call((self._w, 'proxy') + args)) or ()
3843n/a
3844n/a def proxy_coord(self):
3845n/a """Return the x and y pair of the most recent proxy location
3846n/a """
3847n/a return self.proxy("coord")
3848n/a
3849n/a def proxy_forget(self):
3850n/a """Remove the proxy from the display.
3851n/a """
3852n/a return self.proxy("forget")
3853n/a
3854n/a def proxy_place(self, x, y):
3855n/a """Place the proxy at the given x and y coordinates.
3856n/a """
3857n/a return self.proxy("place", x, y)
3858n/a
3859n/a def sash(self, *args):
3860n/a """Internal function."""
3861n/a return self._getints(
3862n/a self.tk.call((self._w, 'sash') + args)) or ()
3863n/a
3864n/a def sash_coord(self, index):
3865n/a """Return the current x and y pair for the sash given by index.
3866n/a
3867n/a Index must be an integer between 0 and 1 less than the
3868n/a number of panes in the panedwindow. The coordinates given are
3869n/a those of the top left corner of the region containing the sash.
3870n/a pathName sash dragto index x y This command computes the
3871n/a difference between the given coordinates and the coordinates
3872n/a given to the last sash coord command for the given sash. It then
3873n/a moves that sash the computed difference. The return value is the
3874n/a empty string.
3875n/a """
3876n/a return self.sash("coord", index)
3877n/a
3878n/a def sash_mark(self, index):
3879n/a """Records x and y for the sash given by index;
3880n/a
3881n/a Used in conjunction with later dragto commands to move the sash.
3882n/a """
3883n/a return self.sash("mark", index)
3884n/a
3885n/a def sash_place(self, index, x, y):
3886n/a """Place the sash given by index at the given coordinates
3887n/a """
3888n/a return self.sash("place", index, x, y)
3889n/a
3890n/a def panecget(self, child, option):
3891n/a """Query a management option for window.
3892n/a
3893n/a Option may be any value allowed by the paneconfigure subcommand
3894n/a """
3895n/a return self.tk.call(
3896n/a (self._w, 'panecget') + (child, '-'+option))
3897n/a
3898n/a def paneconfigure(self, tagOrId, cnf=None, **kw):
3899n/a """Query or modify the management options for window.
3900n/a
3901n/a If no option is specified, returns a list describing all
3902n/a of the available options for pathName. If option is
3903n/a specified with no value, then the command returns a list
3904n/a describing the one named option (this list will be identical
3905n/a to the corresponding sublist of the value returned if no
3906n/a option is specified). If one or more option-value pairs are
3907n/a specified, then the command modifies the given widget
3908n/a option(s) to have the given value(s); in this case the
3909n/a command returns an empty string. The following options
3910n/a are supported:
3911n/a
3912n/a after window
3913n/a Insert the window after the window specified. window
3914n/a should be the name of a window already managed by pathName.
3915n/a before window
3916n/a Insert the window before the window specified. window
3917n/a should be the name of a window already managed by pathName.
3918n/a height size
3919n/a Specify a height for the window. The height will be the
3920n/a outer dimension of the window including its border, if
3921n/a any. If size is an empty string, or if -height is not
3922n/a specified, then the height requested internally by the
3923n/a window will be used initially; the height may later be
3924n/a adjusted by the movement of sashes in the panedwindow.
3925n/a Size may be any value accepted by Tk_GetPixels.
3926n/a minsize n
3927n/a Specifies that the size of the window cannot be made
3928n/a less than n. This constraint only affects the size of
3929n/a the widget in the paned dimension -- the x dimension
3930n/a for horizontal panedwindows, the y dimension for
3931n/a vertical panedwindows. May be any value accepted by
3932n/a Tk_GetPixels.
3933n/a padx n
3934n/a Specifies a non-negative value indicating how much
3935n/a extra space to leave on each side of the window in
3936n/a the X-direction. The value may have any of the forms
3937n/a accepted by Tk_GetPixels.
3938n/a pady n
3939n/a Specifies a non-negative value indicating how much
3940n/a extra space to leave on each side of the window in
3941n/a the Y-direction. The value may have any of the forms
3942n/a accepted by Tk_GetPixels.
3943n/a sticky style
3944n/a If a window's pane is larger than the requested
3945n/a dimensions of the window, this option may be used
3946n/a to position (or stretch) the window within its pane.
3947n/a Style is a string that contains zero or more of the
3948n/a characters n, s, e or w. The string can optionally
3949n/a contains spaces or commas, but they are ignored. Each
3950n/a letter refers to a side (north, south, east, or west)
3951n/a that the window will "stick" to. If both n and s
3952n/a (or e and w) are specified, the window will be
3953n/a stretched to fill the entire height (or width) of
3954n/a its cavity.
3955n/a width size
3956n/a Specify a width for the window. The width will be
3957n/a the outer dimension of the window including its
3958n/a border, if any. If size is an empty string, or
3959n/a if -width is not specified, then the width requested
3960n/a internally by the window will be used initially; the
3961n/a width may later be adjusted by the movement of sashes
3962n/a in the panedwindow. Size may be any value accepted by
3963n/a Tk_GetPixels.
3964n/a
3965n/a """
3966n/a if cnf is None and not kw:
3967n/a return self._getconfigure(self._w, 'paneconfigure', tagOrId)
3968n/a if isinstance(cnf, str) and not kw:
3969n/a return self._getconfigure1(
3970n/a self._w, 'paneconfigure', tagOrId, '-'+cnf)
3971n/a self.tk.call((self._w, 'paneconfigure', tagOrId) +
3972n/a self._options(cnf, kw))
3973n/a paneconfig = paneconfigure
3974n/a
3975n/a def panes(self):
3976n/a """Returns an ordered list of the child panes."""
3977n/a return self.tk.splitlist(self.tk.call(self._w, 'panes'))
3978n/a
3979n/a# Test:
3980n/a
3981n/adef _test():
3982n/a root = Tk()
3983n/a text = "This is Tcl/Tk version %s" % TclVersion
3984n/a text += "\nThis should be a cedilla: \xe7"
3985n/a label = Label(root, text=text)
3986n/a label.pack()
3987n/a test = Button(root, text="Click me!",
3988n/a command=lambda root=root: root.test.configure(
3989n/a text="[%s]" % root.test['text']))
3990n/a test.pack()
3991n/a root.test = test
3992n/a quit = Button(root, text="QUIT", command=root.destroy)
3993n/a quit.pack()
3994n/a # The following three commands are needed so the window pops
3995n/a # up on top on Windows...
3996n/a root.iconify()
3997n/a root.update()
3998n/a root.deiconify()
3999n/a root.mainloop()
4000n/a
4001n/aif __name__ == '__main__':
4002n/a _test()