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