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

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

#countcontent
1n/a"""Ttk wrapper.
2n/a
3n/aThis module provides classes to allow using Tk themed widget set.
4n/a
5n/aTtk is based on a revised and enhanced version of
6n/aTIP #48 (http://tip.tcl.tk/48) specified style engine.
7n/a
8n/aIts basic idea is to separate, to the extent possible, the code
9n/aimplementing a widget's behavior from the code implementing its
10n/aappearance. Widget class bindings are primarily responsible for
11n/amaintaining the widget state and invoking callbacks, all aspects
12n/aof the widgets appearance lies at Themes.
13n/a"""
14n/a
15n/a__version__ = "0.3.1"
16n/a
17n/a__author__ = "Guilherme Polo <ggpolo@gmail.com>"
18n/a
19n/a__all__ = ["Button", "Checkbutton", "Combobox", "Entry", "Frame", "Label",
20n/a "Labelframe", "LabelFrame", "Menubutton", "Notebook", "Panedwindow",
21n/a "PanedWindow", "Progressbar", "Radiobutton", "Scale", "Scrollbar",
22n/a "Separator", "Sizegrip", "Style", "Treeview",
23n/a # Extensions
24n/a "LabeledScale", "OptionMenu",
25n/a # functions
26n/a "tclobjs_to_py", "setup_master"]
27n/a
28n/aimport Tkinter
29n/a
30n/a_flatten = Tkinter._flatten
31n/a
32n/a# Verify if Tk is new enough to not need the Tile package
33n/a_REQUIRE_TILE = True if Tkinter.TkVersion < 8.5 else False
34n/a
35n/adef _load_tile(master):
36n/a if _REQUIRE_TILE:
37n/a import os
38n/a tilelib = os.environ.get('TILE_LIBRARY')
39n/a if tilelib:
40n/a # append custom tile path to the list of directories that
41n/a # Tcl uses when attempting to resolve packages with the package
42n/a # command
43n/a master.tk.eval(
44n/a 'global auto_path; '
45n/a 'lappend auto_path {%s}' % tilelib)
46n/a
47n/a master.tk.eval('package require tile') # TclError may be raised here
48n/a master._tile_loaded = True
49n/a
50n/adef _format_optdict(optdict, script=False, ignore=None):
51n/a """Formats optdict to a tuple to pass it to tk.call.
52n/a
53n/a E.g. (script=False):
54n/a {'foreground': 'blue', 'padding': [1, 2, 3, 4]} returns:
55n/a ('-foreground', 'blue', '-padding', '1 2 3 4')"""
56n/a format = "%s" if not script else "{%s}"
57n/a
58n/a opts = []
59n/a for opt, value in optdict.iteritems():
60n/a if ignore and opt in ignore:
61n/a continue
62n/a
63n/a if isinstance(value, (list, tuple)):
64n/a v = []
65n/a for val in value:
66n/a if isinstance(val, basestring):
67n/a v.append(unicode(val) if val else '{}')
68n/a else:
69n/a v.append(str(val))
70n/a
71n/a # format v according to the script option, but also check for
72n/a # space in any value in v in order to group them correctly
73n/a value = format % ' '.join(
74n/a ('{%s}' if ' ' in val else '%s') % val for val in v)
75n/a
76n/a if script and value == '':
77n/a value = '{}' # empty string in Python is equivalent to {} in Tcl
78n/a
79n/a opts.append(("-%s" % opt, value))
80n/a
81n/a # Remember: _flatten skips over None
82n/a return _flatten(opts)
83n/a
84n/adef _format_mapdict(mapdict, script=False):
85n/a """Formats mapdict to pass it to tk.call.
86n/a
87n/a E.g. (script=False):
88n/a {'expand': [('active', 'selected', 'grey'), ('focus', [1, 2, 3, 4])]}
89n/a
90n/a returns:
91n/a
92n/a ('-expand', '{active selected} grey focus {1, 2, 3, 4}')"""
93n/a # if caller passes a Tcl script to tk.call, all the values need to
94n/a # be grouped into words (arguments to a command in Tcl dialect)
95n/a format = "%s" if not script else "{%s}"
96n/a
97n/a opts = []
98n/a for opt, value in mapdict.iteritems():
99n/a
100n/a opt_val = []
101n/a # each value in mapdict is expected to be a sequence, where each item
102n/a # is another sequence containing a state (or several) and a value
103n/a for statespec in value:
104n/a state, val = statespec[:-1], statespec[-1]
105n/a
106n/a if len(state) > 1: # group multiple states
107n/a state = "{%s}" % ' '.join(state)
108n/a else: # single state
109n/a # if it is empty (something that evaluates to False), then
110n/a # format it to Tcl code to denote the "normal" state
111n/a state = state[0] or '{}'
112n/a
113n/a if isinstance(val, (list, tuple)): # val needs to be grouped
114n/a val = "{%s}" % ' '.join(map(str, val))
115n/a
116n/a opt_val.append("%s %s" % (state, val))
117n/a
118n/a opts.append(("-%s" % opt, format % ' '.join(opt_val)))
119n/a
120n/a return _flatten(opts)
121n/a
122n/adef _format_elemcreate(etype, script=False, *args, **kw):
123n/a """Formats args and kw according to the given element factory etype."""
124n/a spec = None
125n/a opts = ()
126n/a if etype in ("image", "vsapi"):
127n/a if etype == "image": # define an element based on an image
128n/a # first arg should be the default image name
129n/a iname = args[0]
130n/a # next args, if any, are statespec/value pairs which is almost
131n/a # a mapdict, but we just need the value
132n/a imagespec = _format_mapdict({None: args[1:]})[1]
133n/a spec = "%s %s" % (iname, imagespec)
134n/a
135n/a else:
136n/a # define an element whose visual appearance is drawn using the
137n/a # Microsoft Visual Styles API which is responsible for the
138n/a # themed styles on Windows XP and Vista.
139n/a # Availability: Tk 8.6, Windows XP and Vista.
140n/a class_name, part_id = args[:2]
141n/a statemap = _format_mapdict({None: args[2:]})[1]
142n/a spec = "%s %s %s" % (class_name, part_id, statemap)
143n/a
144n/a opts = _format_optdict(kw, script)
145n/a
146n/a elif etype == "from": # clone an element
147n/a # it expects a themename and optionally an element to clone from,
148n/a # otherwise it will clone {} (empty element)
149n/a spec = args[0] # theme name
150n/a if len(args) > 1: # elementfrom specified
151n/a opts = (args[1], )
152n/a
153n/a if script:
154n/a spec = '{%s}' % spec
155n/a opts = ' '.join(map(str, opts))
156n/a
157n/a return spec, opts
158n/a
159n/adef _format_layoutlist(layout, indent=0, indent_size=2):
160n/a """Formats a layout list so we can pass the result to ttk::style
161n/a layout and ttk::style settings. Note that the layout doesn't has to
162n/a be a list necessarily.
163n/a
164n/a E.g.:
165n/a [("Menubutton.background", None),
166n/a ("Menubutton.button", {"children":
167n/a [("Menubutton.focus", {"children":
168n/a [("Menubutton.padding", {"children":
169n/a [("Menubutton.label", {"side": "left", "expand": 1})]
170n/a })]
171n/a })]
172n/a }),
173n/a ("Menubutton.indicator", {"side": "right"})
174n/a ]
175n/a
176n/a returns:
177n/a
178n/a Menubutton.background
179n/a Menubutton.button -children {
180n/a Menubutton.focus -children {
181n/a Menubutton.padding -children {
182n/a Menubutton.label -side left -expand 1
183n/a }
184n/a }
185n/a }
186n/a Menubutton.indicator -side right"""
187n/a script = []
188n/a
189n/a for layout_elem in layout:
190n/a elem, opts = layout_elem
191n/a opts = opts or {}
192n/a fopts = ' '.join(map(str, _format_optdict(opts, True, "children")))
193n/a head = "%s%s%s" % (' ' * indent, elem, (" %s" % fopts) if fopts else '')
194n/a
195n/a if "children" in opts:
196n/a script.append(head + " -children {")
197n/a indent += indent_size
198n/a newscript, indent = _format_layoutlist(opts['children'], indent,
199n/a indent_size)
200n/a script.append(newscript)
201n/a indent -= indent_size
202n/a script.append('%s}' % (' ' * indent))
203n/a else:
204n/a script.append(head)
205n/a
206n/a return '\n'.join(script), indent
207n/a
208n/adef _script_from_settings(settings):
209n/a """Returns an appropriate script, based on settings, according to
210n/a theme_settings definition to be used by theme_settings and
211n/a theme_create."""
212n/a script = []
213n/a # a script will be generated according to settings passed, which
214n/a # will then be evaluated by Tcl
215n/a for name, opts in settings.iteritems():
216n/a # will format specific keys according to Tcl code
217n/a if opts.get('configure'): # format 'configure'
218n/a s = ' '.join(map(unicode, _format_optdict(opts['configure'], True)))
219n/a script.append("ttk::style configure %s %s;" % (name, s))
220n/a
221n/a if opts.get('map'): # format 'map'
222n/a s = ' '.join(map(unicode, _format_mapdict(opts['map'], True)))
223n/a script.append("ttk::style map %s %s;" % (name, s))
224n/a
225n/a if 'layout' in opts: # format 'layout' which may be empty
226n/a if not opts['layout']:
227n/a s = 'null' # could be any other word, but this one makes sense
228n/a else:
229n/a s, _ = _format_layoutlist(opts['layout'])
230n/a script.append("ttk::style layout %s {\n%s\n}" % (name, s))
231n/a
232n/a if opts.get('element create'): # format 'element create'
233n/a eopts = opts['element create']
234n/a etype = eopts[0]
235n/a
236n/a # find where args end, and where kwargs start
237n/a argc = 1 # etype was the first one
238n/a while argc < len(eopts) and not hasattr(eopts[argc], 'iteritems'):
239n/a argc += 1
240n/a
241n/a elemargs = eopts[1:argc]
242n/a elemkw = eopts[argc] if argc < len(eopts) and eopts[argc] else {}
243n/a spec, opts = _format_elemcreate(etype, True, *elemargs, **elemkw)
244n/a
245n/a script.append("ttk::style element create %s %s %s %s" % (
246n/a name, etype, spec, opts))
247n/a
248n/a return '\n'.join(script)
249n/a
250n/adef _dict_from_tcltuple(ttuple, cut_minus=True):
251n/a """Break tuple in pairs, format it properly, then build the return
252n/a dict. If cut_minus is True, the supposed '-' prefixing options will
253n/a be removed.
254n/a
255n/a ttuple is expected to contain an even number of elements."""
256n/a opt_start = 1 if cut_minus else 0
257n/a
258n/a retdict = {}
259n/a it = iter(ttuple)
260n/a for opt, val in zip(it, it):
261n/a retdict[str(opt)[opt_start:]] = val
262n/a
263n/a return tclobjs_to_py(retdict)
264n/a
265n/adef _list_from_statespec(stuple):
266n/a """Construct a list from the given statespec tuple according to the
267n/a accepted statespec accepted by _format_mapdict."""
268n/a nval = []
269n/a for val in stuple:
270n/a typename = getattr(val, 'typename', None)
271n/a if typename is None:
272n/a nval.append(val)
273n/a else: # this is a Tcl object
274n/a val = str(val)
275n/a if typename == 'StateSpec':
276n/a val = val.split()
277n/a nval.append(val)
278n/a
279n/a it = iter(nval)
280n/a return [_flatten(spec) for spec in zip(it, it)]
281n/a
282n/adef _list_from_layouttuple(ltuple):
283n/a """Construct a list from the tuple returned by ttk::layout, this is
284n/a somewhat the reverse of _format_layoutlist."""
285n/a res = []
286n/a
287n/a indx = 0
288n/a while indx < len(ltuple):
289n/a name = ltuple[indx]
290n/a opts = {}
291n/a res.append((name, opts))
292n/a indx += 1
293n/a
294n/a while indx < len(ltuple): # grab name's options
295n/a opt, val = ltuple[indx:indx + 2]
296n/a if not opt.startswith('-'): # found next name
297n/a break
298n/a
299n/a opt = opt[1:] # remove the '-' from the option
300n/a indx += 2
301n/a
302n/a if opt == 'children':
303n/a val = _list_from_layouttuple(val)
304n/a
305n/a opts[opt] = val
306n/a
307n/a return res
308n/a
309n/adef _val_or_dict(options, func, *args):
310n/a """Format options then call func with args and options and return
311n/a the appropriate result.
312n/a
313n/a If no option is specified, a dict is returned. If a option is
314n/a specified with the None value, the value for that option is returned.
315n/a Otherwise, the function just sets the passed options and the caller
316n/a shouldn't be expecting a return value anyway."""
317n/a options = _format_optdict(options)
318n/a res = func(*(args + options))
319n/a
320n/a if len(options) % 2: # option specified without a value, return its value
321n/a return res
322n/a
323n/a return _dict_from_tcltuple(res)
324n/a
325n/adef _convert_stringval(value):
326n/a """Converts a value to, hopefully, a more appropriate Python object."""
327n/a value = unicode(value)
328n/a try:
329n/a value = int(value)
330n/a except (ValueError, TypeError):
331n/a pass
332n/a
333n/a return value
334n/a
335n/adef tclobjs_to_py(adict):
336n/a """Returns adict with its values converted from Tcl objects to Python
337n/a objects."""
338n/a for opt, val in adict.iteritems():
339n/a if val and hasattr(val, '__len__') and not isinstance(val, basestring):
340n/a if getattr(val[0], 'typename', None) == 'StateSpec':
341n/a val = _list_from_statespec(val)
342n/a else:
343n/a val = map(_convert_stringval, val)
344n/a
345n/a elif hasattr(val, 'typename'): # some other (single) Tcl object
346n/a val = _convert_stringval(val)
347n/a
348n/a adict[opt] = val
349n/a
350n/a return adict
351n/a
352n/adef setup_master(master=None):
353n/a """If master is not None, itself is returned. If master is None,
354n/a the default master is returned if there is one, otherwise a new
355n/a master is created and returned.
356n/a
357n/a If it is not allowed to use the default root and master is None,
358n/a RuntimeError is raised."""
359n/a if master is None:
360n/a if Tkinter._support_default_root:
361n/a master = Tkinter._default_root or Tkinter.Tk()
362n/a else:
363n/a raise RuntimeError(
364n/a "No master specified and Tkinter is "
365n/a "configured to not support default root")
366n/a return master
367n/a
368n/a
369n/aclass Style(object):
370n/a """Manipulate style database."""
371n/a
372n/a _name = "ttk::style"
373n/a
374n/a def __init__(self, master=None):
375n/a master = setup_master(master)
376n/a
377n/a if not getattr(master, '_tile_loaded', False):
378n/a # Load tile now, if needed
379n/a _load_tile(master)
380n/a
381n/a self.master = master
382n/a self.tk = self.master.tk
383n/a
384n/a
385n/a def configure(self, style, query_opt=None, **kw):
386n/a """Query or sets the default value of the specified option(s) in
387n/a style.
388n/a
389n/a Each key in kw is an option and each value is either a string or
390n/a a sequence identifying the value for that option."""
391n/a if query_opt is not None:
392n/a kw[query_opt] = None
393n/a return _val_or_dict(kw, self.tk.call, self._name, "configure", style)
394n/a
395n/a
396n/a def map(self, style, query_opt=None, **kw):
397n/a """Query or sets dynamic values of the specified option(s) in
398n/a style.
399n/a
400n/a Each key in kw is an option and each value should be a list or a
401n/a tuple (usually) containing statespecs grouped in tuples, or list,
402n/a or something else of your preference. A statespec is compound of
403n/a one or more states and then a value."""
404n/a if query_opt is not None:
405n/a return _list_from_statespec(
406n/a self.tk.call(self._name, "map", style, '-%s' % query_opt))
407n/a
408n/a return _dict_from_tcltuple(
409n/a self.tk.call(self._name, "map", style, *(_format_mapdict(kw))))
410n/a
411n/a
412n/a def lookup(self, style, option, state=None, default=None):
413n/a """Returns the value specified for option in style.
414n/a
415n/a If state is specified it is expected to be a sequence of one
416n/a or more states. If the default argument is set, it is used as
417n/a a fallback value in case no specification for option is found."""
418n/a state = ' '.join(state) if state else ''
419n/a
420n/a return self.tk.call(self._name, "lookup", style, '-%s' % option,
421n/a state, default)
422n/a
423n/a
424n/a def layout(self, style, layoutspec=None):
425n/a """Define the widget layout for given style. If layoutspec is
426n/a omitted, return the layout specification for given style.
427n/a
428n/a layoutspec is expected to be a list or an object different than
429n/a None that evaluates to False if you want to "turn off" that style.
430n/a If it is a list (or tuple, or something else), each item should be
431n/a a tuple where the first item is the layout name and the second item
432n/a should have the format described below:
433n/a
434n/a LAYOUTS
435n/a
436n/a A layout can contain the value None, if takes no options, or
437n/a a dict of options specifying how to arrange the element.
438n/a The layout mechanism uses a simplified version of the pack
439n/a geometry manager: given an initial cavity, each element is
440n/a allocated a parcel. Valid options/values are:
441n/a
442n/a side: whichside
443n/a Specifies which side of the cavity to place the
444n/a element; one of top, right, bottom or left. If
445n/a omitted, the element occupies the entire cavity.
446n/a
447n/a sticky: nswe
448n/a Specifies where the element is placed inside its
449n/a allocated parcel.
450n/a
451n/a children: [sublayout... ]
452n/a Specifies a list of elements to place inside the
453n/a element. Each element is a tuple (or other sequence)
454n/a where the first item is the layout name, and the other
455n/a is a LAYOUT."""
456n/a lspec = None
457n/a if layoutspec:
458n/a lspec = _format_layoutlist(layoutspec)[0]
459n/a elif layoutspec is not None: # will disable the layout ({}, '', etc)
460n/a lspec = "null" # could be any other word, but this may make sense
461n/a # when calling layout(style) later
462n/a
463n/a return _list_from_layouttuple(
464n/a self.tk.call(self._name, "layout", style, lspec))
465n/a
466n/a
467n/a def element_create(self, elementname, etype, *args, **kw):
468n/a """Create a new element in the current theme of given etype."""
469n/a spec, opts = _format_elemcreate(etype, False, *args, **kw)
470n/a self.tk.call(self._name, "element", "create", elementname, etype,
471n/a spec, *opts)
472n/a
473n/a
474n/a def element_names(self):
475n/a """Returns the list of elements defined in the current theme."""
476n/a return self.tk.call(self._name, "element", "names")
477n/a
478n/a
479n/a def element_options(self, elementname):
480n/a """Return the list of elementname's options."""
481n/a return self.tk.call(self._name, "element", "options", elementname)
482n/a
483n/a
484n/a def theme_create(self, themename, parent=None, settings=None):
485n/a """Creates a new theme.
486n/a
487n/a It is an error if themename already exists. If parent is
488n/a specified, the new theme will inherit styles, elements and
489n/a layouts from the specified parent theme. If settings are present,
490n/a they are expected to have the same syntax used for theme_settings."""
491n/a script = _script_from_settings(settings) if settings else ''
492n/a
493n/a if parent:
494n/a self.tk.call(self._name, "theme", "create", themename,
495n/a "-parent", parent, "-settings", script)
496n/a else:
497n/a self.tk.call(self._name, "theme", "create", themename,
498n/a "-settings", script)
499n/a
500n/a
501n/a def theme_settings(self, themename, settings):
502n/a """Temporarily sets the current theme to themename, apply specified
503n/a settings and then restore the previous theme.
504n/a
505n/a Each key in settings is a style and each value may contain the
506n/a keys 'configure', 'map', 'layout' and 'element create' and they
507n/a are expected to have the same format as specified by the methods
508n/a configure, map, layout and element_create respectively."""
509n/a script = _script_from_settings(settings)
510n/a self.tk.call(self._name, "theme", "settings", themename, script)
511n/a
512n/a
513n/a def theme_names(self):
514n/a """Returns a list of all known themes."""
515n/a return self.tk.call(self._name, "theme", "names")
516n/a
517n/a
518n/a def theme_use(self, themename=None):
519n/a """If themename is None, returns the theme in use, otherwise, set
520n/a the current theme to themename, refreshes all widgets and emits
521n/a a <<ThemeChanged>> event."""
522n/a if themename is None:
523n/a # Starting on Tk 8.6, checking this global is no longer needed
524n/a # since it allows doing self.tk.call(self._name, "theme", "use")
525n/a return self.tk.eval("return $ttk::currentTheme")
526n/a
527n/a # using "ttk::setTheme" instead of "ttk::style theme use" causes
528n/a # the variable currentTheme to be updated, also, ttk::setTheme calls
529n/a # "ttk::style theme use" in order to change theme.
530n/a self.tk.call("ttk::setTheme", themename)
531n/a
532n/a
533n/aclass Widget(Tkinter.Widget):
534n/a """Base class for Tk themed widgets."""
535n/a
536n/a def __init__(self, master, widgetname, kw=None):
537n/a """Constructs a Ttk Widget with the parent master.
538n/a
539n/a STANDARD OPTIONS
540n/a
541n/a class, cursor, takefocus, style
542n/a
543n/a SCROLLABLE WIDGET OPTIONS
544n/a
545n/a xscrollcommand, yscrollcommand
546n/a
547n/a LABEL WIDGET OPTIONS
548n/a
549n/a text, textvariable, underline, image, compound, width
550n/a
551n/a WIDGET STATES
552n/a
553n/a active, disabled, focus, pressed, selected, background,
554n/a readonly, alternate, invalid
555n/a """
556n/a master = setup_master(master)
557n/a if not getattr(master, '_tile_loaded', False):
558n/a # Load tile now, if needed
559n/a _load_tile(master)
560n/a Tkinter.Widget.__init__(self, master, widgetname, kw=kw)
561n/a
562n/a
563n/a def identify(self, x, y):
564n/a """Returns the name of the element at position x, y, or the empty
565n/a string if the point does not lie within any element.
566n/a
567n/a x and y are pixel coordinates relative to the widget."""
568n/a return self.tk.call(self._w, "identify", x, y)
569n/a
570n/a
571n/a def instate(self, statespec, callback=None, *args, **kw):
572n/a """Test the widget's state.
573n/a
574n/a If callback is not specified, returns True if the widget state
575n/a matches statespec and False otherwise. If callback is specified,
576n/a then it will be invoked with *args, **kw if the widget state
577n/a matches statespec. statespec is expected to be a sequence."""
578n/a ret = self.tk.call(self._w, "instate", ' '.join(statespec))
579n/a if ret and callback:
580n/a return callback(*args, **kw)
581n/a
582n/a return bool(ret)
583n/a
584n/a
585n/a def state(self, statespec=None):
586n/a """Modify or inquire widget state.
587n/a
588n/a Widget state is returned if statespec is None, otherwise it is
589n/a set according to the statespec flags and then a new state spec
590n/a is returned indicating which flags were changed. statespec is
591n/a expected to be a sequence."""
592n/a if statespec is not None:
593n/a statespec = ' '.join(statespec)
594n/a
595n/a return self.tk.splitlist(str(self.tk.call(self._w, "state", statespec)))
596n/a
597n/a
598n/aclass Button(Widget):
599n/a """Ttk Button widget, displays a textual label and/or image, and
600n/a evaluates a command when pressed."""
601n/a
602n/a def __init__(self, master=None, **kw):
603n/a """Construct a Ttk Button widget with the parent master.
604n/a
605n/a STANDARD OPTIONS
606n/a
607n/a class, compound, cursor, image, state, style, takefocus,
608n/a text, textvariable, underline, width
609n/a
610n/a WIDGET-SPECIFIC OPTIONS
611n/a
612n/a command, default, width
613n/a """
614n/a Widget.__init__(self, master, "ttk::button", kw)
615n/a
616n/a
617n/a def invoke(self):
618n/a """Invokes the command associated with the button."""
619n/a return self.tk.call(self._w, "invoke")
620n/a
621n/a
622n/aclass Checkbutton(Widget):
623n/a """Ttk Checkbutton widget which is either in on- or off-state."""
624n/a
625n/a def __init__(self, master=None, **kw):
626n/a """Construct a Ttk Checkbutton widget with the parent master.
627n/a
628n/a STANDARD OPTIONS
629n/a
630n/a class, compound, cursor, image, state, style, takefocus,
631n/a text, textvariable, underline, width
632n/a
633n/a WIDGET-SPECIFIC OPTIONS
634n/a
635n/a command, offvalue, onvalue, variable
636n/a """
637n/a Widget.__init__(self, master, "ttk::checkbutton", kw)
638n/a
639n/a
640n/a def invoke(self):
641n/a """Toggles between the selected and deselected states and
642n/a invokes the associated command. If the widget is currently
643n/a selected, sets the option variable to the offvalue option
644n/a and deselects the widget; otherwise, sets the option variable
645n/a to the option onvalue.
646n/a
647n/a Returns the result of the associated command."""
648n/a return self.tk.call(self._w, "invoke")
649n/a
650n/a
651n/aclass Entry(Widget, Tkinter.Entry):
652n/a """Ttk Entry widget displays a one-line text string and allows that
653n/a string to be edited by the user."""
654n/a
655n/a def __init__(self, master=None, widget=None, **kw):
656n/a """Constructs a Ttk Entry widget with the parent master.
657n/a
658n/a STANDARD OPTIONS
659n/a
660n/a class, cursor, style, takefocus, xscrollcommand
661n/a
662n/a WIDGET-SPECIFIC OPTIONS
663n/a
664n/a exportselection, invalidcommand, justify, show, state,
665n/a textvariable, validate, validatecommand, width
666n/a
667n/a VALIDATION MODES
668n/a
669n/a none, key, focus, focusin, focusout, all
670n/a """
671n/a Widget.__init__(self, master, widget or "ttk::entry", kw)
672n/a
673n/a
674n/a def bbox(self, index):
675n/a """Return a tuple of (x, y, width, height) which describes the
676n/a bounding box of the character given by index."""
677n/a return self.tk.call(self._w, "bbox", index)
678n/a
679n/a
680n/a def identify(self, x, y):
681n/a """Returns the name of the element at position x, y, or the
682n/a empty string if the coordinates are outside the window."""
683n/a return self.tk.call(self._w, "identify", x, y)
684n/a
685n/a
686n/a def validate(self):
687n/a """Force revalidation, independent of the conditions specified
688n/a by the validate option. Returns False if validation fails, True
689n/a if it succeeds. Sets or clears the invalid state accordingly."""
690n/a return bool(self.tk.call(self._w, "validate"))
691n/a
692n/a
693n/aclass Combobox(Entry):
694n/a """Ttk Combobox widget combines a text field with a pop-down list of
695n/a values."""
696n/a
697n/a def __init__(self, master=None, **kw):
698n/a """Construct a Ttk Combobox widget with the parent master.
699n/a
700n/a STANDARD OPTIONS
701n/a
702n/a class, cursor, style, takefocus
703n/a
704n/a WIDGET-SPECIFIC OPTIONS
705n/a
706n/a exportselection, justify, height, postcommand, state,
707n/a textvariable, values, width
708n/a """
709n/a # The "values" option may need special formatting, so leave to
710n/a # _format_optdict the responsability to format it
711n/a if "values" in kw:
712n/a kw["values"] = _format_optdict({'v': kw["values"]})[1]
713n/a
714n/a Entry.__init__(self, master, "ttk::combobox", **kw)
715n/a
716n/a
717n/a def __setitem__(self, item, value):
718n/a if item == "values":
719n/a value = _format_optdict({item: value})[1]
720n/a
721n/a Entry.__setitem__(self, item, value)
722n/a
723n/a
724n/a def configure(self, cnf=None, **kw):
725n/a """Custom Combobox configure, created to properly format the values
726n/a option."""
727n/a if "values" in kw:
728n/a kw["values"] = _format_optdict({'v': kw["values"]})[1]
729n/a
730n/a return Entry.configure(self, cnf, **kw)
731n/a
732n/a
733n/a def current(self, newindex=None):
734n/a """If newindex is supplied, sets the combobox value to the
735n/a element at position newindex in the list of values. Otherwise,
736n/a returns the index of the current value in the list of values
737n/a or -1 if the current value does not appear in the list."""
738n/a return self.tk.call(self._w, "current", newindex)
739n/a
740n/a
741n/a def set(self, value):
742n/a """Sets the value of the combobox to value."""
743n/a self.tk.call(self._w, "set", value)
744n/a
745n/a
746n/aclass Frame(Widget):
747n/a """Ttk Frame widget is a container, used to group other widgets
748n/a together."""
749n/a
750n/a def __init__(self, master=None, **kw):
751n/a """Construct a Ttk Frame with parent master.
752n/a
753n/a STANDARD OPTIONS
754n/a
755n/a class, cursor, style, takefocus
756n/a
757n/a WIDGET-SPECIFIC OPTIONS
758n/a
759n/a borderwidth, relief, padding, width, height
760n/a """
761n/a Widget.__init__(self, master, "ttk::frame", kw)
762n/a
763n/a
764n/aclass Label(Widget):
765n/a """Ttk Label widget displays a textual label and/or image."""
766n/a
767n/a def __init__(self, master=None, **kw):
768n/a """Construct a Ttk Label with parent master.
769n/a
770n/a STANDARD OPTIONS
771n/a
772n/a class, compound, cursor, image, style, takefocus, text,
773n/a textvariable, underline, width
774n/a
775n/a WIDGET-SPECIFIC OPTIONS
776n/a
777n/a anchor, background, font, foreground, justify, padding,
778n/a relief, text, wraplength
779n/a """
780n/a Widget.__init__(self, master, "ttk::label", kw)
781n/a
782n/a
783n/aclass Labelframe(Widget):
784n/a """Ttk Labelframe widget is a container used to group other widgets
785n/a together. It has an optional label, which may be a plain text string
786n/a or another widget."""
787n/a
788n/a def __init__(self, master=None, **kw):
789n/a """Construct a Ttk Labelframe with parent master.
790n/a
791n/a STANDARD OPTIONS
792n/a
793n/a class, cursor, style, takefocus
794n/a
795n/a WIDGET-SPECIFIC OPTIONS
796n/a labelanchor, text, underline, padding, labelwidget, width,
797n/a height
798n/a """
799n/a Widget.__init__(self, master, "ttk::labelframe", kw)
800n/a
801n/aLabelFrame = Labelframe # Tkinter name compatibility
802n/a
803n/a
804n/aclass Menubutton(Widget):
805n/a """Ttk Menubutton widget displays a textual label and/or image, and
806n/a displays a menu when pressed."""
807n/a
808n/a def __init__(self, master=None, **kw):
809n/a """Construct a Ttk Menubutton with parent master.
810n/a
811n/a STANDARD OPTIONS
812n/a
813n/a class, compound, cursor, image, state, style, takefocus,
814n/a text, textvariable, underline, width
815n/a
816n/a WIDGET-SPECIFIC OPTIONS
817n/a
818n/a direction, menu
819n/a """
820n/a Widget.__init__(self, master, "ttk::menubutton", kw)
821n/a
822n/a
823n/aclass Notebook(Widget):
824n/a """Ttk Notebook widget manages a collection of windows and displays
825n/a a single one at a time. Each child window is associated with a tab,
826n/a which the user may select to change the currently-displayed window."""
827n/a
828n/a def __init__(self, master=None, **kw):
829n/a """Construct a Ttk Notebook with parent master.
830n/a
831n/a STANDARD OPTIONS
832n/a
833n/a class, cursor, style, takefocus
834n/a
835n/a WIDGET-SPECIFIC OPTIONS
836n/a
837n/a height, padding, width
838n/a
839n/a TAB OPTIONS
840n/a
841n/a state, sticky, padding, text, image, compound, underline
842n/a
843n/a TAB IDENTIFIERS (tab_id)
844n/a
845n/a The tab_id argument found in several methods may take any of
846n/a the following forms:
847n/a
848n/a * An integer between zero and the number of tabs
849n/a * The name of a child window
850n/a * A positional specification of the form "@x,y", which
851n/a defines the tab
852n/a * The string "current", which identifies the
853n/a currently-selected tab
854n/a * The string "end", which returns the number of tabs (only
855n/a valid for method index)
856n/a """
857n/a Widget.__init__(self, master, "ttk::notebook", kw)
858n/a
859n/a
860n/a def add(self, child, **kw):
861n/a """Adds a new tab to the notebook.
862n/a
863n/a If window is currently managed by the notebook but hidden, it is
864n/a restored to its previous position."""
865n/a self.tk.call(self._w, "add", child, *(_format_optdict(kw)))
866n/a
867n/a
868n/a def forget(self, tab_id):
869n/a """Removes the tab specified by tab_id, unmaps and unmanages the
870n/a associated window."""
871n/a self.tk.call(self._w, "forget", tab_id)
872n/a
873n/a
874n/a def hide(self, tab_id):
875n/a """Hides the tab specified by tab_id.
876n/a
877n/a The tab will not be displayed, but the associated window remains
878n/a managed by the notebook and its configuration remembered. Hidden
879n/a tabs may be restored with the add command."""
880n/a self.tk.call(self._w, "hide", tab_id)
881n/a
882n/a
883n/a def identify(self, x, y):
884n/a """Returns the name of the tab element at position x, y, or the
885n/a empty string if none."""
886n/a return self.tk.call(self._w, "identify", x, y)
887n/a
888n/a
889n/a def index(self, tab_id):
890n/a """Returns the numeric index of the tab specified by tab_id, or
891n/a the total number of tabs if tab_id is the string "end"."""
892n/a return self.tk.call(self._w, "index", tab_id)
893n/a
894n/a
895n/a def insert(self, pos, child, **kw):
896n/a """Inserts a pane at the specified position.
897n/a
898n/a pos is either the string end, an integer index, or the name of
899n/a a managed child. If child is already managed by the notebook,
900n/a moves it to the specified position."""
901n/a self.tk.call(self._w, "insert", pos, child, *(_format_optdict(kw)))
902n/a
903n/a
904n/a def select(self, tab_id=None):
905n/a """Selects the specified tab.
906n/a
907n/a The associated child window will be displayed, and the
908n/a previously-selected window (if different) is unmapped. If tab_id
909n/a is omitted, returns the widget name of the currently selected
910n/a pane."""
911n/a return self.tk.call(self._w, "select", tab_id)
912n/a
913n/a
914n/a def tab(self, tab_id, option=None, **kw):
915n/a """Query or modify the options of the specific tab_id.
916n/a
917n/a If kw is not given, returns a dict of the tab option values. If option
918n/a is specified, returns the value of that option. Otherwise, sets the
919n/a options to the corresponding values."""
920n/a if option is not None:
921n/a kw[option] = None
922n/a return _val_or_dict(kw, self.tk.call, self._w, "tab", tab_id)
923n/a
924n/a
925n/a def tabs(self):
926n/a """Returns a list of windows managed by the notebook."""
927n/a return self.tk.call(self._w, "tabs") or ()
928n/a
929n/a
930n/a def enable_traversal(self):
931n/a """Enable keyboard traversal for a toplevel window containing
932n/a this notebook.
933n/a
934n/a This will extend the bindings for the toplevel window containing
935n/a this notebook as follows:
936n/a
937n/a Control-Tab: selects the tab following the currently selected
938n/a one
939n/a
940n/a Shift-Control-Tab: selects the tab preceding the currently
941n/a selected one
942n/a
943n/a Alt-K: where K is the mnemonic (underlined) character of any
944n/a tab, will select that tab.
945n/a
946n/a Multiple notebooks in a single toplevel may be enabled for
947n/a traversal, including nested notebooks. However, notebook traversal
948n/a only works properly if all panes are direct children of the
949n/a notebook."""
950n/a # The only, and good, difference I see is about mnemonics, which works
951n/a # after calling this method. Control-Tab and Shift-Control-Tab always
952n/a # works (here at least).
953n/a self.tk.call("ttk::notebook::enableTraversal", self._w)
954n/a
955n/a
956n/aclass Panedwindow(Widget, Tkinter.PanedWindow):
957n/a """Ttk Panedwindow widget displays a number of subwindows, stacked
958n/a either vertically or horizontally."""
959n/a
960n/a def __init__(self, master=None, **kw):
961n/a """Construct a Ttk Panedwindow with parent master.
962n/a
963n/a STANDARD OPTIONS
964n/a
965n/a class, cursor, style, takefocus
966n/a
967n/a WIDGET-SPECIFIC OPTIONS
968n/a
969n/a orient, width, height
970n/a
971n/a PANE OPTIONS
972n/a
973n/a weight
974n/a """
975n/a Widget.__init__(self, master, "ttk::panedwindow", kw)
976n/a
977n/a
978n/a forget = Tkinter.PanedWindow.forget # overrides Pack.forget
979n/a
980n/a
981n/a def insert(self, pos, child, **kw):
982n/a """Inserts a pane at the specified positions.
983n/a
984n/a pos is either the string end, and integer index, or the name
985n/a of a child. If child is already managed by the paned window,
986n/a moves it to the specified position."""
987n/a self.tk.call(self._w, "insert", pos, child, *(_format_optdict(kw)))
988n/a
989n/a
990n/a def pane(self, pane, option=None, **kw):
991n/a """Query or modify the options of the specified pane.
992n/a
993n/a pane is either an integer index or the name of a managed subwindow.
994n/a If kw is not given, returns a dict of the pane option values. If
995n/a option is specified then the value for that option is returned.
996n/a Otherwise, sets the options to the correspoding values."""
997n/a if option is not None:
998n/a kw[option] = None
999n/a return _val_or_dict(kw, self.tk.call, self._w, "pane", pane)
1000n/a
1001n/a
1002n/a def sashpos(self, index, newpos=None):
1003n/a """If newpos is specified, sets the position of sash number index.
1004n/a
1005n/a May adjust the positions of adjacent sashes to ensure that
1006n/a positions are monotonically increasing. Sash positions are further
1007n/a constrained to be between 0 and the total size of the widget.
1008n/a
1009n/a Returns the new position of sash number index."""
1010n/a return self.tk.call(self._w, "sashpos", index, newpos)
1011n/a
1012n/aPanedWindow = Panedwindow # Tkinter name compatibility
1013n/a
1014n/a
1015n/aclass Progressbar(Widget):
1016n/a """Ttk Progressbar widget shows the status of a long-running
1017n/a operation. They can operate in two modes: determinate mode shows the
1018n/a amount completed relative to the total amount of work to be done, and
1019n/a indeterminate mode provides an animated display to let the user know
1020n/a that something is happening."""
1021n/a
1022n/a def __init__(self, master=None, **kw):
1023n/a """Construct a Ttk Progressbar with parent master.
1024n/a
1025n/a STANDARD OPTIONS
1026n/a
1027n/a class, cursor, style, takefocus
1028n/a
1029n/a WIDGET-SPECIFIC OPTIONS
1030n/a
1031n/a orient, length, mode, maximum, value, variable, phase
1032n/a """
1033n/a Widget.__init__(self, master, "ttk::progressbar", kw)
1034n/a
1035n/a
1036n/a def start(self, interval=None):
1037n/a """Begin autoincrement mode: schedules a recurring timer event
1038n/a that calls method step every interval milliseconds.
1039n/a
1040n/a interval defaults to 50 milliseconds (20 steps/second) if ommited."""
1041n/a self.tk.call(self._w, "start", interval)
1042n/a
1043n/a
1044n/a def step(self, amount=None):
1045n/a """Increments the value option by amount.
1046n/a
1047n/a amount defaults to 1.0 if omitted."""
1048n/a self.tk.call(self._w, "step", amount)
1049n/a
1050n/a
1051n/a def stop(self):
1052n/a """Stop autoincrement mode: cancels any recurring timer event
1053n/a initiated by start."""
1054n/a self.tk.call(self._w, "stop")
1055n/a
1056n/a
1057n/aclass Radiobutton(Widget):
1058n/a """Ttk Radiobutton widgets are used in groups to show or change a
1059n/a set of mutually-exclusive options."""
1060n/a
1061n/a def __init__(self, master=None, **kw):
1062n/a """Construct a Ttk Radiobutton with parent master.
1063n/a
1064n/a STANDARD OPTIONS
1065n/a
1066n/a class, compound, cursor, image, state, style, takefocus,
1067n/a text, textvariable, underline, width
1068n/a
1069n/a WIDGET-SPECIFIC OPTIONS
1070n/a
1071n/a command, value, variable
1072n/a """
1073n/a Widget.__init__(self, master, "ttk::radiobutton", kw)
1074n/a
1075n/a
1076n/a def invoke(self):
1077n/a """Sets the option variable to the option value, selects the
1078n/a widget, and invokes the associated command.
1079n/a
1080n/a Returns the result of the command, or an empty string if
1081n/a no command is specified."""
1082n/a return self.tk.call(self._w, "invoke")
1083n/a
1084n/a
1085n/aclass Scale(Widget, Tkinter.Scale):
1086n/a """Ttk Scale widget is typically used to control the numeric value of
1087n/a a linked variable that varies uniformly over some range."""
1088n/a
1089n/a def __init__(self, master=None, **kw):
1090n/a """Construct a Ttk Scale with parent master.
1091n/a
1092n/a STANDARD OPTIONS
1093n/a
1094n/a class, cursor, style, takefocus
1095n/a
1096n/a WIDGET-SPECIFIC OPTIONS
1097n/a
1098n/a command, from, length, orient, to, value, variable
1099n/a """
1100n/a Widget.__init__(self, master, "ttk::scale", kw)
1101n/a
1102n/a
1103n/a def configure(self, cnf=None, **kw):
1104n/a """Modify or query scale options.
1105n/a
1106n/a Setting a value for any of the "from", "from_" or "to" options
1107n/a generates a <<RangeChanged>> event."""
1108n/a if cnf:
1109n/a kw.update(cnf)
1110n/a Widget.configure(self, **kw)
1111n/a if any(['from' in kw, 'from_' in kw, 'to' in kw]):
1112n/a self.event_generate('<<RangeChanged>>')
1113n/a
1114n/a
1115n/a def get(self, x=None, y=None):
1116n/a """Get the current value of the value option, or the value
1117n/a corresponding to the coordinates x, y if they are specified.
1118n/a
1119n/a x and y are pixel coordinates relative to the scale widget
1120n/a origin."""
1121n/a return self.tk.call(self._w, 'get', x, y)
1122n/a
1123n/a
1124n/aclass Scrollbar(Widget, Tkinter.Scrollbar):
1125n/a """Ttk Scrollbar controls the viewport of a scrollable widget."""
1126n/a
1127n/a def __init__(self, master=None, **kw):
1128n/a """Construct a Ttk Scrollbar with parent master.
1129n/a
1130n/a STANDARD OPTIONS
1131n/a
1132n/a class, cursor, style, takefocus
1133n/a
1134n/a WIDGET-SPECIFIC OPTIONS
1135n/a
1136n/a command, orient
1137n/a """
1138n/a Widget.__init__(self, master, "ttk::scrollbar", kw)
1139n/a
1140n/a
1141n/aclass Separator(Widget):
1142n/a """Ttk Separator widget displays a horizontal or vertical separator
1143n/a bar."""
1144n/a
1145n/a def __init__(self, master=None, **kw):
1146n/a """Construct a Ttk Separator with parent master.
1147n/a
1148n/a STANDARD OPTIONS
1149n/a
1150n/a class, cursor, style, takefocus
1151n/a
1152n/a WIDGET-SPECIFIC OPTIONS
1153n/a
1154n/a orient
1155n/a """
1156n/a Widget.__init__(self, master, "ttk::separator", kw)
1157n/a
1158n/a
1159n/aclass Sizegrip(Widget):
1160n/a """Ttk Sizegrip allows the user to resize the containing toplevel
1161n/a window by pressing and dragging the grip."""
1162n/a
1163n/a def __init__(self, master=None, **kw):
1164n/a """Construct a Ttk Sizegrip with parent master.
1165n/a
1166n/a STANDARD OPTIONS
1167n/a
1168n/a class, cursor, state, style, takefocus
1169n/a """
1170n/a Widget.__init__(self, master, "ttk::sizegrip", kw)
1171n/a
1172n/a
1173n/aclass Treeview(Widget, Tkinter.XView, Tkinter.YView):
1174n/a """Ttk Treeview widget displays a hierarchical collection of items.
1175n/a
1176n/a Each item has a textual label, an optional image, and an optional list
1177n/a of data values. The data values are displayed in successive columns
1178n/a after the tree label."""
1179n/a
1180n/a def __init__(self, master=None, **kw):
1181n/a """Construct a Ttk Treeview with parent master.
1182n/a
1183n/a STANDARD OPTIONS
1184n/a
1185n/a class, cursor, style, takefocus, xscrollcommand,
1186n/a yscrollcommand
1187n/a
1188n/a WIDGET-SPECIFIC OPTIONS
1189n/a
1190n/a columns, displaycolumns, height, padding, selectmode, show
1191n/a
1192n/a ITEM OPTIONS
1193n/a
1194n/a text, image, values, open, tags
1195n/a
1196n/a TAG OPTIONS
1197n/a
1198n/a foreground, background, font, image
1199n/a """
1200n/a Widget.__init__(self, master, "ttk::treeview", kw)
1201n/a
1202n/a
1203n/a def bbox(self, item, column=None):
1204n/a """Returns the bounding box (relative to the treeview widget's
1205n/a window) of the specified item in the form x y width height.
1206n/a
1207n/a If column is specified, returns the bounding box of that cell.
1208n/a If the item is not visible (i.e., if it is a descendant of a
1209n/a closed item or is scrolled offscreen), returns an empty string."""
1210n/a return self.tk.call(self._w, "bbox", item, column)
1211n/a
1212n/a
1213n/a def get_children(self, item=None):
1214n/a """Returns a tuple of children belonging to item.
1215n/a
1216n/a If item is not specified, returns root children."""
1217n/a return self.tk.call(self._w, "children", item or '') or ()
1218n/a
1219n/a
1220n/a def set_children(self, item, *newchildren):
1221n/a """Replaces item's child with newchildren.
1222n/a
1223n/a Children present in item that are not present in newchildren
1224n/a are detached from tree. No items in newchildren may be an
1225n/a ancestor of item."""
1226n/a self.tk.call(self._w, "children", item, newchildren)
1227n/a
1228n/a
1229n/a def column(self, column, option=None, **kw):
1230n/a """Query or modify the options for the specified column.
1231n/a
1232n/a If kw is not given, returns a dict of the column option values. If
1233n/a option is specified then the value for that option is returned.
1234n/a Otherwise, sets the options to the corresponding values."""
1235n/a if option is not None:
1236n/a kw[option] = None
1237n/a return _val_or_dict(kw, self.tk.call, self._w, "column", column)
1238n/a
1239n/a
1240n/a def delete(self, *items):
1241n/a """Delete all specified items and all their descendants. The root
1242n/a item may not be deleted."""
1243n/a self.tk.call(self._w, "delete", items)
1244n/a
1245n/a
1246n/a def detach(self, *items):
1247n/a """Unlinks all of the specified items from the tree.
1248n/a
1249n/a The items and all of their descendants are still present, and may
1250n/a be reinserted at another point in the tree, but will not be
1251n/a displayed. The root item may not be detached."""
1252n/a self.tk.call(self._w, "detach", items)
1253n/a
1254n/a
1255n/a def exists(self, item):
1256n/a """Returns True if the specified item is present in the three,
1257n/a False otherwise."""
1258n/a return bool(self.tk.call(self._w, "exists", item))
1259n/a
1260n/a
1261n/a def focus(self, item=None):
1262n/a """If item is specified, sets the focus item to item. Otherwise,
1263n/a returns the current focus item, or '' if there is none."""
1264n/a return self.tk.call(self._w, "focus", item)
1265n/a
1266n/a
1267n/a def heading(self, column, option=None, **kw):
1268n/a """Query or modify the heading options for the specified column.
1269n/a
1270n/a If kw is not given, returns a dict of the heading option values. If
1271n/a option is specified then the value for that option is returned.
1272n/a Otherwise, sets the options to the corresponding values.
1273n/a
1274n/a Valid options/values are:
1275n/a text: text
1276n/a The text to display in the column heading
1277n/a image: image_name
1278n/a Specifies an image to display to the right of the column
1279n/a heading
1280n/a anchor: anchor
1281n/a Specifies how the heading text should be aligned. One of
1282n/a the standard Tk anchor values
1283n/a command: callback
1284n/a A callback to be invoked when the heading label is
1285n/a pressed.
1286n/a
1287n/a To configure the tree column heading, call this with column = "#0" """
1288n/a cmd = kw.get('command')
1289n/a if cmd and not isinstance(cmd, basestring):
1290n/a # callback not registered yet, do it now
1291n/a kw['command'] = self.master.register(cmd, self._substitute)
1292n/a
1293n/a if option is not None:
1294n/a kw[option] = None
1295n/a
1296n/a return _val_or_dict(kw, self.tk.call, self._w, 'heading', column)
1297n/a
1298n/a
1299n/a def identify(self, component, x, y):
1300n/a """Returns a description of the specified component under the
1301n/a point given by x and y, or the empty string if no such component
1302n/a is present at that position."""
1303n/a return self.tk.call(self._w, "identify", component, x, y)
1304n/a
1305n/a
1306n/a def identify_row(self, y):
1307n/a """Returns the item ID of the item at position y."""
1308n/a return self.identify("row", 0, y)
1309n/a
1310n/a
1311n/a def identify_column(self, x):
1312n/a """Returns the data column identifier of the cell at position x.
1313n/a
1314n/a The tree column has ID #0."""
1315n/a return self.identify("column", x, 0)
1316n/a
1317n/a
1318n/a def identify_region(self, x, y):
1319n/a """Returns one of:
1320n/a
1321n/a heading: Tree heading area.
1322n/a separator: Space between two columns headings;
1323n/a tree: The tree area.
1324n/a cell: A data cell.
1325n/a
1326n/a * Availability: Tk 8.6"""
1327n/a return self.identify("region", x, y)
1328n/a
1329n/a
1330n/a def identify_element(self, x, y):
1331n/a """Returns the element at position x, y.
1332n/a
1333n/a * Availability: Tk 8.6"""
1334n/a return self.identify("element", x, y)
1335n/a
1336n/a
1337n/a def index(self, item):
1338n/a """Returns the integer index of item within its parent's list
1339n/a of children."""
1340n/a return self.tk.call(self._w, "index", item)
1341n/a
1342n/a
1343n/a def insert(self, parent, index, iid=None, **kw):
1344n/a """Creates a new item and return the item identifier of the newly
1345n/a created item.
1346n/a
1347n/a parent is the item ID of the parent item, or the empty string
1348n/a to create a new top-level item. index is an integer, or the value
1349n/a end, specifying where in the list of parent's children to insert
1350n/a the new item. If index is less than or equal to zero, the new node
1351n/a is inserted at the beginning, if index is greater than or equal to
1352n/a the current number of children, it is inserted at the end. If iid
1353n/a is specified, it is used as the item identifier, iid must not
1354n/a already exist in the tree. Otherwise, a new unique identifier
1355n/a is generated."""
1356n/a opts = _format_optdict(kw)
1357n/a if iid:
1358n/a res = self.tk.call(self._w, "insert", parent, index,
1359n/a "-id", iid, *opts)
1360n/a else:
1361n/a res = self.tk.call(self._w, "insert", parent, index, *opts)
1362n/a
1363n/a return res
1364n/a
1365n/a
1366n/a def item(self, item, option=None, **kw):
1367n/a """Query or modify the options for the specified item.
1368n/a
1369n/a If no options are given, a dict with options/values for the item
1370n/a is returned. If option is specified then the value for that option
1371n/a is returned. Otherwise, sets the options to the corresponding
1372n/a values as given by kw."""
1373n/a if option is not None:
1374n/a kw[option] = None
1375n/a return _val_or_dict(kw, self.tk.call, self._w, "item", item)
1376n/a
1377n/a
1378n/a def move(self, item, parent, index):
1379n/a """Moves item to position index in parent's list of children.
1380n/a
1381n/a It is illegal to move an item under one of its descendants. If
1382n/a index is less than or equal to zero, item is moved to the
1383n/a beginning, if greater than or equal to the number of children,
1384n/a it is moved to the end. If item was detached it is reattached."""
1385n/a self.tk.call(self._w, "move", item, parent, index)
1386n/a
1387n/a reattach = move # A sensible method name for reattaching detached items
1388n/a
1389n/a
1390n/a def next(self, item):
1391n/a """Returns the identifier of item's next sibling, or '' if item
1392n/a is the last child of its parent."""
1393n/a return self.tk.call(self._w, "next", item)
1394n/a
1395n/a
1396n/a def parent(self, item):
1397n/a """Returns the ID of the parent of item, or '' if item is at the
1398n/a top level of the hierarchy."""
1399n/a return self.tk.call(self._w, "parent", item)
1400n/a
1401n/a
1402n/a def prev(self, item):
1403n/a """Returns the identifier of item's previous sibling, or '' if
1404n/a item is the first child of its parent."""
1405n/a return self.tk.call(self._w, "prev", item)
1406n/a
1407n/a
1408n/a def see(self, item):
1409n/a """Ensure that item is visible.
1410n/a
1411n/a Sets all of item's ancestors open option to True, and scrolls
1412n/a the widget if necessary so that item is within the visible
1413n/a portion of the tree."""
1414n/a self.tk.call(self._w, "see", item)
1415n/a
1416n/a
1417n/a def selection(self, selop=None, items=None):
1418n/a """If selop is not specified, returns selected items."""
1419n/a return self.tk.call(self._w, "selection", selop, items)
1420n/a
1421n/a
1422n/a def selection_set(self, items):
1423n/a """items becomes the new selection."""
1424n/a self.selection("set", items)
1425n/a
1426n/a
1427n/a def selection_add(self, items):
1428n/a """Add items to the selection."""
1429n/a self.selection("add", items)
1430n/a
1431n/a
1432n/a def selection_remove(self, items):
1433n/a """Remove items from the selection."""
1434n/a self.selection("remove", items)
1435n/a
1436n/a
1437n/a def selection_toggle(self, items):
1438n/a """Toggle the selection state of each item in items."""
1439n/a self.selection("toggle", items)
1440n/a
1441n/a
1442n/a def set(self, item, column=None, value=None):
1443n/a """With one argument, returns a dictionary of column/value pairs
1444n/a for the specified item. With two arguments, returns the current
1445n/a value of the specified column. With three arguments, sets the
1446n/a value of given column in given item to the specified value."""
1447n/a res = self.tk.call(self._w, "set", item, column, value)
1448n/a if column is None and value is None:
1449n/a return _dict_from_tcltuple(res, False)
1450n/a else:
1451n/a return res
1452n/a
1453n/a
1454n/a def tag_bind(self, tagname, sequence=None, callback=None):
1455n/a """Bind a callback for the given event sequence to the tag tagname.
1456n/a When an event is delivered to an item, the callbacks for each
1457n/a of the item's tags option are called."""
1458n/a self._bind((self._w, "tag", "bind", tagname), sequence, callback, add=0)
1459n/a
1460n/a
1461n/a def tag_configure(self, tagname, option=None, **kw):
1462n/a """Query or modify the options for the specified tagname.
1463n/a
1464n/a If kw is not given, returns a dict of the option settings for tagname.
1465n/a If option is specified, returns the value for that option for the
1466n/a specified tagname. Otherwise, sets the options to the corresponding
1467n/a values for the given tagname."""
1468n/a if option is not None:
1469n/a kw[option] = None
1470n/a return _val_or_dict(kw, self.tk.call, self._w, "tag", "configure",
1471n/a tagname)
1472n/a
1473n/a
1474n/a def tag_has(self, tagname, item=None):
1475n/a """If item is specified, returns 1 or 0 depending on whether the
1476n/a specified item has the given tagname. Otherwise, returns a list of
1477n/a all items which have the specified tag.
1478n/a
1479n/a * Availability: Tk 8.6"""
1480n/a return self.tk.call(self._w, "tag", "has", tagname, item)
1481n/a
1482n/a
1483n/a# Extensions
1484n/a
1485n/aclass LabeledScale(Frame, object):
1486n/a """A Ttk Scale widget with a Ttk Label widget indicating its
1487n/a current value.
1488n/a
1489n/a The Ttk Scale can be accessed through instance.scale, and Ttk Label
1490n/a can be accessed through instance.label"""
1491n/a
1492n/a def __init__(self, master=None, variable=None, from_=0, to=10, **kw):
1493n/a """Construct an horizontal LabeledScale with parent master, a
1494n/a variable to be associated with the Ttk Scale widget and its range.
1495n/a If variable is not specified, a Tkinter.IntVar is created.
1496n/a
1497n/a WIDGET-SPECIFIC OPTIONS
1498n/a
1499n/a compound: 'top' or 'bottom'
1500n/a Specifies how to display the label relative to the scale.
1501n/a Defaults to 'top'.
1502n/a """
1503n/a self._label_top = kw.pop('compound', 'top') == 'top'
1504n/a
1505n/a Frame.__init__(self, master, **kw)
1506n/a self._variable = variable or Tkinter.IntVar(master)
1507n/a self._variable.set(from_)
1508n/a self._last_valid = from_
1509n/a
1510n/a self.label = Label(self)
1511n/a self.scale = Scale(self, variable=self._variable, from_=from_, to=to)
1512n/a self.scale.bind('<<RangeChanged>>', self._adjust)
1513n/a
1514n/a # position scale and label according to the compound option
1515n/a scale_side = 'bottom' if self._label_top else 'top'
1516n/a label_side = 'top' if scale_side == 'bottom' else 'bottom'
1517n/a self.scale.pack(side=scale_side, fill='x')
1518n/a tmp = Label(self).pack(side=label_side) # place holder
1519n/a self.label.place(anchor='n' if label_side == 'top' else 's')
1520n/a
1521n/a # update the label as scale or variable changes
1522n/a self.__tracecb = self._variable.trace_variable('w', self._adjust)
1523n/a self.bind('<Configure>', self._adjust)
1524n/a self.bind('<Map>', self._adjust)
1525n/a
1526n/a
1527n/a def destroy(self):
1528n/a """Destroy this widget and possibly its associated variable."""
1529n/a try:
1530n/a self._variable.trace_vdelete('w', self.__tracecb)
1531n/a except AttributeError:
1532n/a # widget has been destroyed already
1533n/a pass
1534n/a else:
1535n/a del self._variable
1536n/a Frame.destroy(self)
1537n/a
1538n/a
1539n/a def _adjust(self, *args):
1540n/a """Adjust the label position according to the scale."""
1541n/a def adjust_label():
1542n/a self.update_idletasks() # "force" scale redraw
1543n/a
1544n/a x, y = self.scale.coords()
1545n/a if self._label_top:
1546n/a y = self.scale.winfo_y() - self.label.winfo_reqheight()
1547n/a else:
1548n/a y = self.scale.winfo_reqheight() + self.label.winfo_reqheight()
1549n/a
1550n/a self.label.place_configure(x=x, y=y)
1551n/a
1552n/a from_, to = self.scale['from'], self.scale['to']
1553n/a if to < from_:
1554n/a from_, to = to, from_
1555n/a newval = self._variable.get()
1556n/a if not from_ <= newval <= to:
1557n/a # value outside range, set value back to the last valid one
1558n/a self.value = self._last_valid
1559n/a return
1560n/a
1561n/a self._last_valid = newval
1562n/a self.label['text'] = newval
1563n/a self.after_idle(adjust_label)
1564n/a
1565n/a
1566n/a def _get_value(self):
1567n/a """Return current scale value."""
1568n/a return self._variable.get()
1569n/a
1570n/a
1571n/a def _set_value(self, val):
1572n/a """Set new scale value."""
1573n/a self._variable.set(val)
1574n/a
1575n/a
1576n/a value = property(_get_value, _set_value)
1577n/a
1578n/a
1579n/aclass OptionMenu(Menubutton):
1580n/a """Themed OptionMenu, based after Tkinter's OptionMenu, which allows
1581n/a the user to select a value from a menu."""
1582n/a
1583n/a def __init__(self, master, variable, default=None, *values, **kwargs):
1584n/a """Construct a themed OptionMenu widget with master as the parent,
1585n/a the resource textvariable set to variable, the initially selected
1586n/a value specified by the default parameter, the menu values given by
1587n/a *values and additional keywords.
1588n/a
1589n/a WIDGET-SPECIFIC OPTIONS
1590n/a
1591n/a style: stylename
1592n/a Menubutton style.
1593n/a direction: 'above', 'below', 'left', 'right', or 'flush'
1594n/a Menubutton direction.
1595n/a command: callback
1596n/a A callback that will be invoked after selecting an item.
1597n/a """
1598n/a kw = {'textvariable': variable, 'style': kwargs.pop('style', None),
1599n/a 'direction': kwargs.pop('direction', None)}
1600n/a Menubutton.__init__(self, master, **kw)
1601n/a self['menu'] = Tkinter.Menu(self, tearoff=False)
1602n/a
1603n/a self._variable = variable
1604n/a self._callback = kwargs.pop('command', None)
1605n/a if kwargs:
1606n/a raise Tkinter.TclError('unknown option -%s' % (
1607n/a kwargs.iterkeys().next()))
1608n/a
1609n/a self.set_menu(default, *values)
1610n/a
1611n/a
1612n/a def __getitem__(self, item):
1613n/a if item == 'menu':
1614n/a return self.nametowidget(Menubutton.__getitem__(self, item))
1615n/a
1616n/a return Menubutton.__getitem__(self, item)
1617n/a
1618n/a
1619n/a def set_menu(self, default=None, *values):
1620n/a """Build a new menu of radiobuttons with *values and optionally
1621n/a a default value."""
1622n/a menu = self['menu']
1623n/a menu.delete(0, 'end')
1624n/a for val in values:
1625n/a menu.add_radiobutton(label=val,
1626n/a command=Tkinter._setit(self._variable, val, self._callback))
1627n/a
1628n/a if default:
1629n/a self._variable.set(default)
1630n/a
1631n/a
1632n/a def destroy(self):
1633n/a """Destroy this widget and its associated variable."""
1634n/a del self._variable
1635n/a Menubutton.destroy(self)