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

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