blob: df813971b4aa77dac25260c3f5a5b6795b466a51 [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."""
280 res = []
281
282 indx = 0
283 while indx < len(ltuple):
284 name = ltuple[indx]
285 opts = {}
286 res.append((name, opts))
287 indx += 1
288
289 while indx < len(ltuple): # grab name's options
290 opt, val = ltuple[indx:indx + 2]
291 if not opt.startswith('-'): # found next name
292 break
293
294 opt = opt[1:] # remove the '-' from the option
295 indx += 2
296
297 if opt == 'children':
Serhiy Storchakaedb64282014-05-28 18:38:15 +0300298 if not tk.wantobjects():
299 val = tk.splitlist(val)
300 val = _list_from_layouttuple(tk, val)
Guilherme Polocda93aa2009-01-28 13:09:03 +0000301
302 opts[opt] = val
303
304 return res
305
Serhiy Storchakaedb64282014-05-28 18:38:15 +0300306def _val_or_dict(tk, options, *args):
307 """Format options then call Tk command with args and options and return
Guilherme Polocda93aa2009-01-28 13:09:03 +0000308 the appropriate result.
309
310 If no option is specified, a dict is returned. If a option is
311 specified with the None value, the value for that option is returned.
312 Otherwise, the function just sets the passed options and the caller
313 shouldn't be expecting a return value anyway."""
314 options = _format_optdict(options)
Serhiy Storchakaedb64282014-05-28 18:38:15 +0300315 res = tk.call(*(args + options))
Guilherme Polocda93aa2009-01-28 13:09:03 +0000316
317 if len(options) % 2: # option specified without a value, return its value
318 return res
319
Serhiy Storchakaedb64282014-05-28 18:38:15 +0300320 return _dict_from_tcltuple(tk.splitlist(res))
Guilherme Polocda93aa2009-01-28 13:09:03 +0000321
322def _convert_stringval(value):
323 """Converts a value to, hopefully, a more appropriate Python object."""
324 value = unicode(value)
325 try:
326 value = int(value)
327 except (ValueError, TypeError):
328 pass
329
330 return value
331
Serhiy Storchaka9be238d2014-01-07 19:32:58 +0200332def _to_number(x):
333 if isinstance(x, str):
334 if '.' in x:
335 x = float(x)
336 else:
337 x = int(x)
338 return x
339
Guilherme Polocda93aa2009-01-28 13:09:03 +0000340def tclobjs_to_py(adict):
341 """Returns adict with its values converted from Tcl objects to Python
342 objects."""
343 for opt, val in adict.iteritems():
344 if val and hasattr(val, '__len__') and not isinstance(val, basestring):
345 if getattr(val[0], 'typename', None) == 'StateSpec':
346 val = _list_from_statespec(val)
347 else:
348 val = map(_convert_stringval, val)
349
350 elif hasattr(val, 'typename'): # some other (single) Tcl object
351 val = _convert_stringval(val)
352
353 adict[opt] = val
354
355 return adict
356
Guilherme Polo190c35f2009-02-09 16:09:17 +0000357def setup_master(master=None):
358 """If master is not None, itself is returned. If master is None,
359 the default master is returned if there is one, otherwise a new
360 master is created and returned.
361
362 If it is not allowed to use the default root and master is None,
363 RuntimeError is raised."""
364 if master is None:
365 if Tkinter._support_default_root:
366 master = Tkinter._default_root or Tkinter.Tk()
367 else:
368 raise RuntimeError(
369 "No master specified and Tkinter is "
370 "configured to not support default root")
371 return master
372
Guilherme Polocda93aa2009-01-28 13:09:03 +0000373
374class Style(object):
375 """Manipulate style database."""
376
377 _name = "ttk::style"
378
379 def __init__(self, master=None):
Guilherme Polo190c35f2009-02-09 16:09:17 +0000380 master = setup_master(master)
Guilherme Polo8e5e4382009-02-07 02:20:29 +0000381
382 if not getattr(master, '_tile_loaded', False):
383 # Load tile now, if needed
384 _load_tile(master)
Guilherme Polocda93aa2009-01-28 13:09:03 +0000385
386 self.master = master
387 self.tk = self.master.tk
388
389
390 def configure(self, style, query_opt=None, **kw):
391 """Query or sets the default value of the specified option(s) in
392 style.
393
394 Each key in kw is an option and each value is either a string or
395 a sequence identifying the value for that option."""
396 if query_opt is not None:
397 kw[query_opt] = None
Serhiy Storchakaedb64282014-05-28 18:38:15 +0300398 return _val_or_dict(self.tk, kw, self._name, "configure", style)
Guilherme Polocda93aa2009-01-28 13:09:03 +0000399
400
401 def map(self, style, query_opt=None, **kw):
402 """Query or sets dynamic values of the specified option(s) in
403 style.
404
405 Each key in kw is an option and each value should be a list or a
406 tuple (usually) containing statespecs grouped in tuples, or list,
407 or something else of your preference. A statespec is compound of
408 one or more states and then a value."""
409 if query_opt is not None:
Serhiy Storchaka9be238d2014-01-07 19:32:58 +0200410 return _list_from_statespec(self.tk.splitlist(
411 self.tk.call(self._name, "map", style, '-%s' % query_opt)))
Guilherme Polocda93aa2009-01-28 13:09:03 +0000412
413 return _dict_from_tcltuple(
414 self.tk.call(self._name, "map", style, *(_format_mapdict(kw))))
415
416
417 def lookup(self, style, option, state=None, default=None):
418 """Returns the value specified for option in style.
419
420 If state is specified it is expected to be a sequence of one
421 or more states. If the default argument is set, it is used as
422 a fallback value in case no specification for option is found."""
423 state = ' '.join(state) if state else ''
424
425 return self.tk.call(self._name, "lookup", style, '-%s' % option,
426 state, default)
427
428
429 def layout(self, style, layoutspec=None):
430 """Define the widget layout for given style. If layoutspec is
431 omitted, return the layout specification for given style.
432
433 layoutspec is expected to be a list or an object different than
434 None that evaluates to False if you want to "turn off" that style.
435 If it is a list (or tuple, or something else), each item should be
436 a tuple where the first item is the layout name and the second item
437 should have the format described below:
438
439 LAYOUTS
440
441 A layout can contain the value None, if takes no options, or
442 a dict of options specifying how to arrange the element.
443 The layout mechanism uses a simplified version of the pack
444 geometry manager: given an initial cavity, each element is
445 allocated a parcel. Valid options/values are:
446
447 side: whichside
448 Specifies which side of the cavity to place the
449 element; one of top, right, bottom or left. If
450 omitted, the element occupies the entire cavity.
451
452 sticky: nswe
453 Specifies where the element is placed inside its
454 allocated parcel.
455
456 children: [sublayout... ]
457 Specifies a list of elements to place inside the
458 element. Each element is a tuple (or other sequence)
459 where the first item is the layout name, and the other
460 is a LAYOUT."""
461 lspec = None
462 if layoutspec:
463 lspec = _format_layoutlist(layoutspec)[0]
464 elif layoutspec is not None: # will disable the layout ({}, '', etc)
465 lspec = "null" # could be any other word, but this may make sense
466 # when calling layout(style) later
467
Serhiy Storchakaedb64282014-05-28 18:38:15 +0300468 return _list_from_layouttuple(self.tk, self.tk.splitlist(
Serhiy Storchaka9be238d2014-01-07 19:32:58 +0200469 self.tk.call(self._name, "layout", style, lspec)))
Guilherme Polocda93aa2009-01-28 13:09:03 +0000470
471
472 def element_create(self, elementname, etype, *args, **kw):
473 """Create a new element in the current theme of given etype."""
474 spec, opts = _format_elemcreate(etype, False, *args, **kw)
475 self.tk.call(self._name, "element", "create", elementname, etype,
476 spec, *opts)
477
478
479 def element_names(self):
480 """Returns the list of elements defined in the current theme."""
Serhiy Storchaka9be238d2014-01-07 19:32:58 +0200481 return self.tk.splitlist(self.tk.call(self._name, "element", "names"))
Guilherme Polocda93aa2009-01-28 13:09:03 +0000482
483
484 def element_options(self, elementname):
485 """Return the list of elementname's options."""
Serhiy Storchaka9be238d2014-01-07 19:32:58 +0200486 return self.tk.splitlist(self.tk.call(self._name, "element", "options", elementname))
Guilherme Polocda93aa2009-01-28 13:09:03 +0000487
488
489 def theme_create(self, themename, parent=None, settings=None):
490 """Creates a new theme.
491
492 It is an error if themename already exists. If parent is
493 specified, the new theme will inherit styles, elements and
494 layouts from the specified parent theme. If settings are present,
495 they are expected to have the same syntax used for theme_settings."""
496 script = _script_from_settings(settings) if settings else ''
497
498 if parent:
499 self.tk.call(self._name, "theme", "create", themename,
500 "-parent", parent, "-settings", script)
501 else:
502 self.tk.call(self._name, "theme", "create", themename,
503 "-settings", script)
504
505
506 def theme_settings(self, themename, settings):
507 """Temporarily sets the current theme to themename, apply specified
508 settings and then restore the previous theme.
509
510 Each key in settings is a style and each value may contain the
511 keys 'configure', 'map', 'layout' and 'element create' and they
512 are expected to have the same format as specified by the methods
513 configure, map, layout and element_create respectively."""
514 script = _script_from_settings(settings)
515 self.tk.call(self._name, "theme", "settings", themename, script)
516
517
518 def theme_names(self):
519 """Returns a list of all known themes."""
Serhiy Storchaka9be238d2014-01-07 19:32:58 +0200520 return self.tk.splitlist(self.tk.call(self._name, "theme", "names"))
Guilherme Polocda93aa2009-01-28 13:09:03 +0000521
522
523 def theme_use(self, themename=None):
524 """If themename is None, returns the theme in use, otherwise, set
525 the current theme to themename, refreshes all widgets and emits
526 a <<ThemeChanged>> event."""
527 if themename is None:
528 # Starting on Tk 8.6, checking this global is no longer needed
529 # since it allows doing self.tk.call(self._name, "theme", "use")
530 return self.tk.eval("return $ttk::currentTheme")
531
532 # using "ttk::setTheme" instead of "ttk::style theme use" causes
533 # the variable currentTheme to be updated, also, ttk::setTheme calls
534 # "ttk::style theme use" in order to change theme.
535 self.tk.call("ttk::setTheme", themename)
536
537
538class Widget(Tkinter.Widget):
539 """Base class for Tk themed widgets."""
540
541 def __init__(self, master, widgetname, kw=None):
542 """Constructs a Ttk Widget with the parent master.
543
544 STANDARD OPTIONS
545
546 class, cursor, takefocus, style
547
548 SCROLLABLE WIDGET OPTIONS
549
550 xscrollcommand, yscrollcommand
551
552 LABEL WIDGET OPTIONS
553
554 text, textvariable, underline, image, compound, width
555
556 WIDGET STATES
557
558 active, disabled, focus, pressed, selected, background,
559 readonly, alternate, invalid
560 """
Guilherme Polo190c35f2009-02-09 16:09:17 +0000561 master = setup_master(master)
Guilherme Polo8e5e4382009-02-07 02:20:29 +0000562 if not getattr(master, '_tile_loaded', False):
563 # Load tile now, if needed
564 _load_tile(master)
Guilherme Polocda93aa2009-01-28 13:09:03 +0000565 Tkinter.Widget.__init__(self, master, widgetname, kw=kw)
566
567
568 def identify(self, x, y):
569 """Returns the name of the element at position x, y, or the empty
570 string if the point does not lie within any element.
571
572 x and y are pixel coordinates relative to the widget."""
573 return self.tk.call(self._w, "identify", x, y)
574
575
576 def instate(self, statespec, callback=None, *args, **kw):
577 """Test the widget's state.
578
579 If callback is not specified, returns True if the widget state
580 matches statespec and False otherwise. If callback is specified,
581 then it will be invoked with *args, **kw if the widget state
582 matches statespec. statespec is expected to be a sequence."""
Serhiy Storchaka9be238d2014-01-07 19:32:58 +0200583 ret = self.tk.getboolean(
584 self.tk.call(self._w, "instate", ' '.join(statespec)))
Guilherme Polocda93aa2009-01-28 13:09:03 +0000585 if ret and callback:
586 return callback(*args, **kw)
587
588 return bool(ret)
589
590
591 def state(self, statespec=None):
592 """Modify or inquire widget state.
593
594 Widget state is returned if statespec is None, otherwise it is
595 set according to the statespec flags and then a new state spec
596 is returned indicating which flags were changed. statespec is
597 expected to be a sequence."""
598 if statespec is not None:
599 statespec = ' '.join(statespec)
600
601 return self.tk.splitlist(str(self.tk.call(self._w, "state", statespec)))
602
603
604class Button(Widget):
605 """Ttk Button widget, displays a textual label and/or image, and
606 evaluates a command when pressed."""
607
608 def __init__(self, master=None, **kw):
609 """Construct a Ttk Button widget with the parent master.
610
611 STANDARD OPTIONS
612
613 class, compound, cursor, image, state, style, takefocus,
614 text, textvariable, underline, width
615
616 WIDGET-SPECIFIC OPTIONS
617
618 command, default, width
619 """
620 Widget.__init__(self, master, "ttk::button", kw)
621
622
623 def invoke(self):
624 """Invokes the command associated with the button."""
625 return self.tk.call(self._w, "invoke")
626
627
628class Checkbutton(Widget):
629 """Ttk Checkbutton widget which is either in on- or off-state."""
630
631 def __init__(self, master=None, **kw):
632 """Construct a Ttk Checkbutton widget with the parent master.
633
634 STANDARD OPTIONS
635
636 class, compound, cursor, image, state, style, takefocus,
637 text, textvariable, underline, width
638
639 WIDGET-SPECIFIC OPTIONS
640
641 command, offvalue, onvalue, variable
642 """
643 Widget.__init__(self, master, "ttk::checkbutton", kw)
644
645
646 def invoke(self):
647 """Toggles between the selected and deselected states and
648 invokes the associated command. If the widget is currently
649 selected, sets the option variable to the offvalue option
650 and deselects the widget; otherwise, sets the option variable
651 to the option onvalue.
652
653 Returns the result of the associated command."""
654 return self.tk.call(self._w, "invoke")
655
656
657class Entry(Widget, Tkinter.Entry):
658 """Ttk Entry widget displays a one-line text string and allows that
659 string to be edited by the user."""
660
661 def __init__(self, master=None, widget=None, **kw):
662 """Constructs a Ttk Entry widget with the parent master.
663
664 STANDARD OPTIONS
665
666 class, cursor, style, takefocus, xscrollcommand
667
668 WIDGET-SPECIFIC OPTIONS
669
670 exportselection, invalidcommand, justify, show, state,
671 textvariable, validate, validatecommand, width
672
673 VALIDATION MODES
674
675 none, key, focus, focusin, focusout, all
676 """
677 Widget.__init__(self, master, widget or "ttk::entry", kw)
678
679
680 def bbox(self, index):
681 """Return a tuple of (x, y, width, height) which describes the
682 bounding box of the character given by index."""
Serhiy Storchaka9be238d2014-01-07 19:32:58 +0200683 return self._getints(self.tk.call(self._w, "bbox", index))
Guilherme Polocda93aa2009-01-28 13:09:03 +0000684
685
686 def identify(self, x, y):
687 """Returns the name of the element at position x, y, or the
688 empty string if the coordinates are outside the window."""
689 return self.tk.call(self._w, "identify", x, y)
690
691
692 def validate(self):
693 """Force revalidation, independent of the conditions specified
694 by the validate option. Returns False if validation fails, True
695 if it succeeds. Sets or clears the invalid state accordingly."""
Serhiy Storchaka9be238d2014-01-07 19:32:58 +0200696 return bool(self.tk.getboolean(self.tk.call(self._w, "validate")))
Guilherme Polocda93aa2009-01-28 13:09:03 +0000697
698
699class Combobox(Entry):
700 """Ttk Combobox widget combines a text field with a pop-down list of
701 values."""
702
703 def __init__(self, master=None, **kw):
704 """Construct a Ttk Combobox widget with the parent master.
705
706 STANDARD OPTIONS
707
708 class, cursor, style, takefocus
709
710 WIDGET-SPECIFIC OPTIONS
711
712 exportselection, justify, height, postcommand, state,
713 textvariable, values, width
714 """
Guilherme Polocda93aa2009-01-28 13:09:03 +0000715 Entry.__init__(self, master, "ttk::combobox", **kw)
716
717
Guilherme Polocda93aa2009-01-28 13:09:03 +0000718 def current(self, newindex=None):
719 """If newindex is supplied, sets the combobox value to the
720 element at position newindex in the list of values. Otherwise,
721 returns the index of the current value in the list of values
722 or -1 if the current value does not appear in the list."""
Serhiy Storchaka9be238d2014-01-07 19:32:58 +0200723 if newindex is None:
724 return self.tk.getint(self.tk.call(self._w, "current"))
Guilherme Polocda93aa2009-01-28 13:09:03 +0000725 return self.tk.call(self._w, "current", newindex)
726
727
728 def set(self, value):
729 """Sets the value of the combobox to value."""
730 self.tk.call(self._w, "set", value)
731
732
733class Frame(Widget):
734 """Ttk Frame widget is a container, used to group other widgets
735 together."""
736
737 def __init__(self, master=None, **kw):
738 """Construct a Ttk Frame with parent master.
739
740 STANDARD OPTIONS
741
742 class, cursor, style, takefocus
743
744 WIDGET-SPECIFIC OPTIONS
745
746 borderwidth, relief, padding, width, height
747 """
748 Widget.__init__(self, master, "ttk::frame", kw)
749
750
751class Label(Widget):
752 """Ttk Label widget displays a textual label and/or image."""
753
754 def __init__(self, master=None, **kw):
755 """Construct a Ttk Label with parent master.
756
757 STANDARD OPTIONS
758
759 class, compound, cursor, image, style, takefocus, text,
760 textvariable, underline, width
761
762 WIDGET-SPECIFIC OPTIONS
763
764 anchor, background, font, foreground, justify, padding,
765 relief, text, wraplength
766 """
767 Widget.__init__(self, master, "ttk::label", kw)
768
769
770class Labelframe(Widget):
771 """Ttk Labelframe widget is a container used to group other widgets
772 together. It has an optional label, which may be a plain text string
773 or another widget."""
774
775 def __init__(self, master=None, **kw):
776 """Construct a Ttk Labelframe with parent master.
777
778 STANDARD OPTIONS
779
780 class, cursor, style, takefocus
781
782 WIDGET-SPECIFIC OPTIONS
783 labelanchor, text, underline, padding, labelwidget, width,
784 height
785 """
786 Widget.__init__(self, master, "ttk::labelframe", kw)
787
788LabelFrame = Labelframe # Tkinter name compatibility
789
790
791class Menubutton(Widget):
792 """Ttk Menubutton widget displays a textual label and/or image, and
793 displays a menu when pressed."""
794
795 def __init__(self, master=None, **kw):
796 """Construct a Ttk Menubutton with parent master.
797
798 STANDARD OPTIONS
799
800 class, compound, cursor, image, state, style, takefocus,
801 text, textvariable, underline, width
802
803 WIDGET-SPECIFIC OPTIONS
804
805 direction, menu
806 """
807 Widget.__init__(self, master, "ttk::menubutton", kw)
808
809
810class Notebook(Widget):
811 """Ttk Notebook widget manages a collection of windows and displays
812 a single one at a time. Each child window is associated with a tab,
813 which the user may select to change the currently-displayed window."""
814
815 def __init__(self, master=None, **kw):
816 """Construct a Ttk Notebook with parent master.
817
818 STANDARD OPTIONS
819
820 class, cursor, style, takefocus
821
822 WIDGET-SPECIFIC OPTIONS
823
824 height, padding, width
825
826 TAB OPTIONS
827
828 state, sticky, padding, text, image, compound, underline
829
830 TAB IDENTIFIERS (tab_id)
831
832 The tab_id argument found in several methods may take any of
833 the following forms:
834
835 * An integer between zero and the number of tabs
836 * The name of a child window
837 * A positional specification of the form "@x,y", which
838 defines the tab
839 * The string "current", which identifies the
840 currently-selected tab
841 * The string "end", which returns the number of tabs (only
842 valid for method index)
843 """
844 Widget.__init__(self, master, "ttk::notebook", kw)
845
846
847 def add(self, child, **kw):
848 """Adds a new tab to the notebook.
849
850 If window is currently managed by the notebook but hidden, it is
851 restored to its previous position."""
852 self.tk.call(self._w, "add", child, *(_format_optdict(kw)))
853
854
855 def forget(self, tab_id):
856 """Removes the tab specified by tab_id, unmaps and unmanages the
857 associated window."""
858 self.tk.call(self._w, "forget", tab_id)
859
860
861 def hide(self, tab_id):
862 """Hides the tab specified by tab_id.
863
864 The tab will not be displayed, but the associated window remains
865 managed by the notebook and its configuration remembered. Hidden
866 tabs may be restored with the add command."""
867 self.tk.call(self._w, "hide", tab_id)
868
869
870 def identify(self, x, y):
871 """Returns the name of the tab element at position x, y, or the
872 empty string if none."""
873 return self.tk.call(self._w, "identify", x, y)
874
875
876 def index(self, tab_id):
877 """Returns the numeric index of the tab specified by tab_id, or
878 the total number of tabs if tab_id is the string "end"."""
Serhiy Storchaka9be238d2014-01-07 19:32:58 +0200879 return self.tk.getint(self.tk.call(self._w, "index", tab_id))
Guilherme Polocda93aa2009-01-28 13:09:03 +0000880
881
882 def insert(self, pos, child, **kw):
883 """Inserts a pane at the specified position.
884
885 pos is either the string end, an integer index, or the name of
886 a managed child. If child is already managed by the notebook,
887 moves it to the specified position."""
888 self.tk.call(self._w, "insert", pos, child, *(_format_optdict(kw)))
889
890
891 def select(self, tab_id=None):
892 """Selects the specified tab.
893
894 The associated child window will be displayed, and the
895 previously-selected window (if different) is unmapped. If tab_id
896 is omitted, returns the widget name of the currently selected
897 pane."""
898 return self.tk.call(self._w, "select", tab_id)
899
900
901 def tab(self, tab_id, option=None, **kw):
902 """Query or modify the options of the specific tab_id.
903
904 If kw is not given, returns a dict of the tab option values. If option
905 is specified, returns the value of that option. Otherwise, sets the
906 options to the corresponding values."""
907 if option is not None:
908 kw[option] = None
Serhiy Storchakaedb64282014-05-28 18:38:15 +0300909 return _val_or_dict(self.tk, kw, self._w, "tab", tab_id)
Guilherme Polocda93aa2009-01-28 13:09:03 +0000910
911
912 def tabs(self):
913 """Returns a list of windows managed by the notebook."""
Serhiy Storchaka9be238d2014-01-07 19:32:58 +0200914 return self.tk.splitlist(self.tk.call(self._w, "tabs") or ())
Guilherme Polocda93aa2009-01-28 13:09:03 +0000915
916
917 def enable_traversal(self):
918 """Enable keyboard traversal for a toplevel window containing
919 this notebook.
920
921 This will extend the bindings for the toplevel window containing
922 this notebook as follows:
923
924 Control-Tab: selects the tab following the currently selected
925 one
926
927 Shift-Control-Tab: selects the tab preceding the currently
928 selected one
929
930 Alt-K: where K is the mnemonic (underlined) character of any
931 tab, will select that tab.
932
933 Multiple notebooks in a single toplevel may be enabled for
934 traversal, including nested notebooks. However, notebook traversal
935 only works properly if all panes are direct children of the
936 notebook."""
937 # The only, and good, difference I see is about mnemonics, which works
938 # after calling this method. Control-Tab and Shift-Control-Tab always
939 # works (here at least).
940 self.tk.call("ttk::notebook::enableTraversal", self._w)
941
942
943class Panedwindow(Widget, Tkinter.PanedWindow):
944 """Ttk Panedwindow widget displays a number of subwindows, stacked
945 either vertically or horizontally."""
946
947 def __init__(self, master=None, **kw):
948 """Construct a Ttk Panedwindow with parent master.
949
950 STANDARD OPTIONS
951
952 class, cursor, style, takefocus
953
954 WIDGET-SPECIFIC OPTIONS
955
956 orient, width, height
957
958 PANE OPTIONS
959
960 weight
961 """
962 Widget.__init__(self, master, "ttk::panedwindow", kw)
963
964
965 forget = Tkinter.PanedWindow.forget # overrides Pack.forget
966
967
968 def insert(self, pos, child, **kw):
969 """Inserts a pane at the specified positions.
970
971 pos is either the string end, and integer index, or the name
972 of a child. If child is already managed by the paned window,
973 moves it to the specified position."""
974 self.tk.call(self._w, "insert", pos, child, *(_format_optdict(kw)))
975
976
977 def pane(self, pane, option=None, **kw):
978 """Query or modify the options of the specified pane.
979
980 pane is either an integer index or the name of a managed subwindow.
981 If kw is not given, returns a dict of the pane option values. If
982 option is specified then the value for that option is returned.
Ezio Melotti24b07bc2011-03-15 18:55:01 +0200983 Otherwise, sets the options to the corresponding values."""
Guilherme Polocda93aa2009-01-28 13:09:03 +0000984 if option is not None:
985 kw[option] = None
Serhiy Storchakaedb64282014-05-28 18:38:15 +0300986 return _val_or_dict(self.tk, kw, self._w, "pane", pane)
Guilherme Polocda93aa2009-01-28 13:09:03 +0000987
988
989 def sashpos(self, index, newpos=None):
990 """If newpos is specified, sets the position of sash number index.
991
992 May adjust the positions of adjacent sashes to ensure that
993 positions are monotonically increasing. Sash positions are further
994 constrained to be between 0 and the total size of the widget.
995
996 Returns the new position of sash number index."""
Serhiy Storchaka9be238d2014-01-07 19:32:58 +0200997 return self.tk.getint(self.tk.call(self._w, "sashpos", index, newpos))
Guilherme Polocda93aa2009-01-28 13:09:03 +0000998
999PanedWindow = Panedwindow # Tkinter name compatibility
1000
1001
1002class Progressbar(Widget):
1003 """Ttk Progressbar widget shows the status of a long-running
1004 operation. They can operate in two modes: determinate mode shows the
1005 amount completed relative to the total amount of work to be done, and
1006 indeterminate mode provides an animated display to let the user know
1007 that something is happening."""
1008
1009 def __init__(self, master=None, **kw):
1010 """Construct a Ttk Progressbar with parent master.
1011
1012 STANDARD OPTIONS
1013
1014 class, cursor, style, takefocus
1015
1016 WIDGET-SPECIFIC OPTIONS
1017
1018 orient, length, mode, maximum, value, variable, phase
1019 """
1020 Widget.__init__(self, master, "ttk::progressbar", kw)
1021
1022
1023 def start(self, interval=None):
1024 """Begin autoincrement mode: schedules a recurring timer event
1025 that calls method step every interval milliseconds.
1026
1027 interval defaults to 50 milliseconds (20 steps/second) if ommited."""
1028 self.tk.call(self._w, "start", interval)
1029
1030
1031 def step(self, amount=None):
1032 """Increments the value option by amount.
1033
1034 amount defaults to 1.0 if omitted."""
1035 self.tk.call(self._w, "step", amount)
1036
1037
1038 def stop(self):
1039 """Stop autoincrement mode: cancels any recurring timer event
1040 initiated by start."""
1041 self.tk.call(self._w, "stop")
1042
1043
1044class Radiobutton(Widget):
1045 """Ttk Radiobutton widgets are used in groups to show or change a
1046 set of mutually-exclusive options."""
1047
1048 def __init__(self, master=None, **kw):
1049 """Construct a Ttk Radiobutton with parent master.
1050
1051 STANDARD OPTIONS
1052
1053 class, compound, cursor, image, state, style, takefocus,
1054 text, textvariable, underline, width
1055
1056 WIDGET-SPECIFIC OPTIONS
1057
1058 command, value, variable
1059 """
1060 Widget.__init__(self, master, "ttk::radiobutton", kw)
1061
1062
1063 def invoke(self):
1064 """Sets the option variable to the option value, selects the
1065 widget, and invokes the associated command.
1066
1067 Returns the result of the command, or an empty string if
1068 no command is specified."""
1069 return self.tk.call(self._w, "invoke")
1070
1071
1072class Scale(Widget, Tkinter.Scale):
1073 """Ttk Scale widget is typically used to control the numeric value of
1074 a linked variable that varies uniformly over some range."""
1075
1076 def __init__(self, master=None, **kw):
1077 """Construct a Ttk Scale with parent master.
1078
1079 STANDARD OPTIONS
1080
1081 class, cursor, style, takefocus
1082
1083 WIDGET-SPECIFIC OPTIONS
1084
1085 command, from, length, orient, to, value, variable
1086 """
1087 Widget.__init__(self, master, "ttk::scale", kw)
1088
1089
1090 def configure(self, cnf=None, **kw):
1091 """Modify or query scale options.
1092
1093 Setting a value for any of the "from", "from_" or "to" options
1094 generates a <<RangeChanged>> event."""
1095 if cnf:
1096 kw.update(cnf)
1097 Widget.configure(self, **kw)
1098 if any(['from' in kw, 'from_' in kw, 'to' in kw]):
1099 self.event_generate('<<RangeChanged>>')
1100
1101
1102 def get(self, x=None, y=None):
1103 """Get the current value of the value option, or the value
1104 corresponding to the coordinates x, y if they are specified.
1105
1106 x and y are pixel coordinates relative to the scale widget
1107 origin."""
1108 return self.tk.call(self._w, 'get', x, y)
1109
1110
1111class Scrollbar(Widget, Tkinter.Scrollbar):
1112 """Ttk Scrollbar controls the viewport of a scrollable widget."""
1113
1114 def __init__(self, master=None, **kw):
1115 """Construct a Ttk Scrollbar with parent master.
1116
1117 STANDARD OPTIONS
1118
1119 class, cursor, style, takefocus
1120
1121 WIDGET-SPECIFIC OPTIONS
1122
1123 command, orient
1124 """
1125 Widget.__init__(self, master, "ttk::scrollbar", kw)
1126
1127
1128class Separator(Widget):
1129 """Ttk Separator widget displays a horizontal or vertical separator
1130 bar."""
1131
1132 def __init__(self, master=None, **kw):
1133 """Construct a Ttk Separator with parent master.
1134
1135 STANDARD OPTIONS
1136
1137 class, cursor, style, takefocus
1138
1139 WIDGET-SPECIFIC OPTIONS
1140
1141 orient
1142 """
1143 Widget.__init__(self, master, "ttk::separator", kw)
1144
1145
1146class Sizegrip(Widget):
1147 """Ttk Sizegrip allows the user to resize the containing toplevel
1148 window by pressing and dragging the grip."""
1149
1150 def __init__(self, master=None, **kw):
1151 """Construct a Ttk Sizegrip with parent master.
1152
1153 STANDARD OPTIONS
1154
1155 class, cursor, state, style, takefocus
1156 """
1157 Widget.__init__(self, master, "ttk::sizegrip", kw)
1158
1159
Guilherme Poloe45f0172009-08-14 14:36:45 +00001160class Treeview(Widget, Tkinter.XView, Tkinter.YView):
Guilherme Polocda93aa2009-01-28 13:09:03 +00001161 """Ttk Treeview widget displays a hierarchical collection of items.
1162
1163 Each item has a textual label, an optional image, and an optional list
1164 of data values. The data values are displayed in successive columns
1165 after the tree label."""
1166
1167 def __init__(self, master=None, **kw):
1168 """Construct a Ttk Treeview with parent master.
1169
1170 STANDARD OPTIONS
1171
1172 class, cursor, style, takefocus, xscrollcommand,
1173 yscrollcommand
1174
1175 WIDGET-SPECIFIC OPTIONS
1176
1177 columns, displaycolumns, height, padding, selectmode, show
1178
1179 ITEM OPTIONS
1180
1181 text, image, values, open, tags
1182
1183 TAG OPTIONS
1184
1185 foreground, background, font, image
1186 """
1187 Widget.__init__(self, master, "ttk::treeview", kw)
1188
1189
1190 def bbox(self, item, column=None):
1191 """Returns the bounding box (relative to the treeview widget's
1192 window) of the specified item in the form x y width height.
1193
1194 If column is specified, returns the bounding box of that cell.
1195 If the item is not visible (i.e., if it is a descendant of a
1196 closed item or is scrolled offscreen), returns an empty string."""
Serhiy Storchaka9be238d2014-01-07 19:32:58 +02001197 return self._getints(self.tk.call(self._w, "bbox", item, column)) or ''
Guilherme Polocda93aa2009-01-28 13:09:03 +00001198
1199
1200 def get_children(self, item=None):
1201 """Returns a tuple of children belonging to item.
1202
1203 If item is not specified, returns root children."""
Serhiy Storchaka9be238d2014-01-07 19:32:58 +02001204 return self.tk.splitlist(
1205 self.tk.call(self._w, "children", item or '') or ())
Guilherme Polocda93aa2009-01-28 13:09:03 +00001206
1207
1208 def set_children(self, item, *newchildren):
1209 """Replaces item's child with newchildren.
1210
1211 Children present in item that are not present in newchildren
1212 are detached from tree. No items in newchildren may be an
1213 ancestor of item."""
1214 self.tk.call(self._w, "children", item, newchildren)
1215
1216
1217 def column(self, column, option=None, **kw):
1218 """Query or modify the options for the specified column.
1219
1220 If kw is not given, returns a dict of the column option values. If
1221 option is specified then the value for that option is returned.
1222 Otherwise, sets the options to the corresponding values."""
1223 if option is not None:
1224 kw[option] = None
Serhiy Storchakaedb64282014-05-28 18:38:15 +03001225 return _val_or_dict(self.tk, kw, self._w, "column", column)
Guilherme Polocda93aa2009-01-28 13:09:03 +00001226
1227
1228 def delete(self, *items):
1229 """Delete all specified items and all their descendants. The root
1230 item may not be deleted."""
1231 self.tk.call(self._w, "delete", items)
1232
1233
1234 def detach(self, *items):
1235 """Unlinks all of the specified items from the tree.
1236
1237 The items and all of their descendants are still present, and may
1238 be reinserted at another point in the tree, but will not be
1239 displayed. The root item may not be detached."""
1240 self.tk.call(self._w, "detach", items)
1241
1242
1243 def exists(self, item):
Georg Brandlf14a2bf2012-04-04 20:19:09 +02001244 """Returns True if the specified item is present in the tree,
Guilherme Polocda93aa2009-01-28 13:09:03 +00001245 False otherwise."""
Serhiy Storchaka9be238d2014-01-07 19:32:58 +02001246 return bool(self.tk.getboolean(self.tk.call(self._w, "exists", item)))
Guilherme Polocda93aa2009-01-28 13:09:03 +00001247
1248
1249 def focus(self, item=None):
1250 """If item is specified, sets the focus item to item. Otherwise,
1251 returns the current focus item, or '' if there is none."""
1252 return self.tk.call(self._w, "focus", item)
1253
1254
1255 def heading(self, column, option=None, **kw):
1256 """Query or modify the heading options for the specified column.
1257
1258 If kw is not given, returns a dict of the heading option values. If
1259 option is specified then the value for that option is returned.
1260 Otherwise, sets the options to the corresponding values.
1261
1262 Valid options/values are:
1263 text: text
1264 The text to display in the column heading
1265 image: image_name
1266 Specifies an image to display to the right of the column
1267 heading
1268 anchor: anchor
1269 Specifies how the heading text should be aligned. One of
1270 the standard Tk anchor values
1271 command: callback
1272 A callback to be invoked when the heading label is
1273 pressed.
1274
1275 To configure the tree column heading, call this with column = "#0" """
1276 cmd = kw.get('command')
1277 if cmd and not isinstance(cmd, basestring):
1278 # callback not registered yet, do it now
1279 kw['command'] = self.master.register(cmd, self._substitute)
1280
1281 if option is not None:
1282 kw[option] = None
1283
Serhiy Storchakaedb64282014-05-28 18:38:15 +03001284 return _val_or_dict(self.tk, kw, self._w, 'heading', column)
Guilherme Polocda93aa2009-01-28 13:09:03 +00001285
1286
1287 def identify(self, component, x, y):
1288 """Returns a description of the specified component under the
1289 point given by x and y, or the empty string if no such component
1290 is present at that position."""
1291 return self.tk.call(self._w, "identify", component, x, y)
1292
1293
1294 def identify_row(self, y):
1295 """Returns the item ID of the item at position y."""
1296 return self.identify("row", 0, y)
1297
1298
1299 def identify_column(self, x):
1300 """Returns the data column identifier of the cell at position x.
1301
1302 The tree column has ID #0."""
1303 return self.identify("column", x, 0)
1304
1305
1306 def identify_region(self, x, y):
1307 """Returns one of:
1308
1309 heading: Tree heading area.
1310 separator: Space between two columns headings;
1311 tree: The tree area.
1312 cell: A data cell.
1313
1314 * Availability: Tk 8.6"""
1315 return self.identify("region", x, y)
1316
1317
1318 def identify_element(self, x, y):
1319 """Returns the element at position x, y.
1320
1321 * Availability: Tk 8.6"""
1322 return self.identify("element", x, y)
1323
1324
1325 def index(self, item):
1326 """Returns the integer index of item within its parent's list
1327 of children."""
Serhiy Storchaka9be238d2014-01-07 19:32:58 +02001328 return self.tk.getint(self.tk.call(self._w, "index", item))
Guilherme Polocda93aa2009-01-28 13:09:03 +00001329
1330
1331 def insert(self, parent, index, iid=None, **kw):
1332 """Creates a new item and return the item identifier of the newly
1333 created item.
1334
1335 parent is the item ID of the parent item, or the empty string
1336 to create a new top-level item. index is an integer, or the value
1337 end, specifying where in the list of parent's children to insert
1338 the new item. If index is less than or equal to zero, the new node
1339 is inserted at the beginning, if index is greater than or equal to
1340 the current number of children, it is inserted at the end. If iid
1341 is specified, it is used as the item identifier, iid must not
1342 already exist in the tree. Otherwise, a new unique identifier
1343 is generated."""
1344 opts = _format_optdict(kw)
1345 if iid:
1346 res = self.tk.call(self._w, "insert", parent, index,
1347 "-id", iid, *opts)
1348 else:
1349 res = self.tk.call(self._w, "insert", parent, index, *opts)
1350
1351 return res
1352
1353
1354 def item(self, item, option=None, **kw):
1355 """Query or modify the options for the specified item.
1356
1357 If no options are given, a dict with options/values for the item
1358 is returned. If option is specified then the value for that option
1359 is returned. Otherwise, sets the options to the corresponding
1360 values as given by kw."""
1361 if option is not None:
1362 kw[option] = None
Serhiy Storchakaedb64282014-05-28 18:38:15 +03001363 return _val_or_dict(self.tk, kw, self._w, "item", item)
Guilherme Polocda93aa2009-01-28 13:09:03 +00001364
1365
1366 def move(self, item, parent, index):
1367 """Moves item to position index in parent's list of children.
1368
1369 It is illegal to move an item under one of its descendants. If
1370 index is less than or equal to zero, item is moved to the
1371 beginning, if greater than or equal to the number of children,
1372 it is moved to the end. If item was detached it is reattached."""
1373 self.tk.call(self._w, "move", item, parent, index)
1374
1375 reattach = move # A sensible method name for reattaching detached items
1376
1377
1378 def next(self, item):
1379 """Returns the identifier of item's next sibling, or '' if item
1380 is the last child of its parent."""
1381 return self.tk.call(self._w, "next", item)
1382
1383
1384 def parent(self, item):
1385 """Returns the ID of the parent of item, or '' if item is at the
1386 top level of the hierarchy."""
1387 return self.tk.call(self._w, "parent", item)
1388
1389
1390 def prev(self, item):
1391 """Returns the identifier of item's previous sibling, or '' if
1392 item is the first child of its parent."""
1393 return self.tk.call(self._w, "prev", item)
1394
1395
1396 def see(self, item):
1397 """Ensure that item is visible.
1398
1399 Sets all of item's ancestors open option to True, and scrolls
1400 the widget if necessary so that item is within the visible
1401 portion of the tree."""
1402 self.tk.call(self._w, "see", item)
1403
1404
1405 def selection(self, selop=None, items=None):
1406 """If selop is not specified, returns selected items."""
1407 return self.tk.call(self._w, "selection", selop, items)
1408
1409
1410 def selection_set(self, items):
1411 """items becomes the new selection."""
1412 self.selection("set", items)
1413
1414
1415 def selection_add(self, items):
1416 """Add items to the selection."""
1417 self.selection("add", items)
1418
1419
1420 def selection_remove(self, items):
1421 """Remove items from the selection."""
1422 self.selection("remove", items)
1423
1424
1425 def selection_toggle(self, items):
1426 """Toggle the selection state of each item in items."""
1427 self.selection("toggle", items)
1428
1429
1430 def set(self, item, column=None, value=None):
1431 """With one argument, returns a dictionary of column/value pairs
1432 for the specified item. With two arguments, returns the current
1433 value of the specified column. With three arguments, sets the
1434 value of given column in given item to the specified value."""
1435 res = self.tk.call(self._w, "set", item, column, value)
1436 if column is None and value is None:
Serhiy Storchaka9be238d2014-01-07 19:32:58 +02001437 return _dict_from_tcltuple(self.tk.splitlist(res), False)
Guilherme Polocda93aa2009-01-28 13:09:03 +00001438 else:
1439 return res
1440
1441
1442 def tag_bind(self, tagname, sequence=None, callback=None):
1443 """Bind a callback for the given event sequence to the tag tagname.
1444 When an event is delivered to an item, the callbacks for each
1445 of the item's tags option are called."""
1446 self._bind((self._w, "tag", "bind", tagname), sequence, callback, add=0)
1447
1448
1449 def tag_configure(self, tagname, option=None, **kw):
1450 """Query or modify the options for the specified tagname.
1451
1452 If kw is not given, returns a dict of the option settings for tagname.
1453 If option is specified, returns the value for that option for the
1454 specified tagname. Otherwise, sets the options to the corresponding
1455 values for the given tagname."""
1456 if option is not None:
1457 kw[option] = None
Serhiy Storchakaedb64282014-05-28 18:38:15 +03001458 return _val_or_dict(self.tk, kw, self._w, "tag", "configure",
Guilherme Polocda93aa2009-01-28 13:09:03 +00001459 tagname)
1460
1461
1462 def tag_has(self, tagname, item=None):
1463 """If item is specified, returns 1 or 0 depending on whether the
1464 specified item has the given tagname. Otherwise, returns a list of
1465 all items which have the specified tag.
1466
1467 * Availability: Tk 8.6"""
Serhiy Storchaka9be238d2014-01-07 19:32:58 +02001468 return self.tk.getboolean(
1469 self.tk.call(self._w, "tag", "has", tagname, item))
Guilherme Polocda93aa2009-01-28 13:09:03 +00001470
1471
Guilherme Polocda93aa2009-01-28 13:09:03 +00001472# Extensions
1473
1474class LabeledScale(Frame, object):
1475 """A Ttk Scale widget with a Ttk Label widget indicating its
1476 current value.
1477
1478 The Ttk Scale can be accessed through instance.scale, and Ttk Label
1479 can be accessed through instance.label"""
1480
1481 def __init__(self, master=None, variable=None, from_=0, to=10, **kw):
1482 """Construct an horizontal LabeledScale with parent master, a
1483 variable to be associated with the Ttk Scale widget and its range.
1484 If variable is not specified, a Tkinter.IntVar is created.
1485
1486 WIDGET-SPECIFIC OPTIONS
1487
1488 compound: 'top' or 'bottom'
1489 Specifies how to display the label relative to the scale.
1490 Defaults to 'top'.
1491 """
1492 self._label_top = kw.pop('compound', 'top') == 'top'
1493
1494 Frame.__init__(self, master, **kw)
1495 self._variable = variable or Tkinter.IntVar(master)
1496 self._variable.set(from_)
1497 self._last_valid = from_
1498
1499 self.label = Label(self)
1500 self.scale = Scale(self, variable=self._variable, from_=from_, to=to)
1501 self.scale.bind('<<RangeChanged>>', self._adjust)
1502
1503 # position scale and label according to the compound option
1504 scale_side = 'bottom' if self._label_top else 'top'
1505 label_side = 'top' if scale_side == 'bottom' else 'bottom'
1506 self.scale.pack(side=scale_side, fill='x')
1507 tmp = Label(self).pack(side=label_side) # place holder
1508 self.label.place(anchor='n' if label_side == 'top' else 's')
1509
1510 # update the label as scale or variable changes
1511 self.__tracecb = self._variable.trace_variable('w', self._adjust)
1512 self.bind('<Configure>', self._adjust)
1513 self.bind('<Map>', self._adjust)
1514
1515
1516 def destroy(self):
1517 """Destroy this widget and possibly its associated variable."""
1518 try:
1519 self._variable.trace_vdelete('w', self.__tracecb)
1520 except AttributeError:
1521 # widget has been destroyed already
1522 pass
1523 else:
1524 del self._variable
1525 Frame.destroy(self)
1526
1527
1528 def _adjust(self, *args):
1529 """Adjust the label position according to the scale."""
1530 def adjust_label():
1531 self.update_idletasks() # "force" scale redraw
1532
1533 x, y = self.scale.coords()
1534 if self._label_top:
1535 y = self.scale.winfo_y() - self.label.winfo_reqheight()
1536 else:
1537 y = self.scale.winfo_reqheight() + self.label.winfo_reqheight()
1538
1539 self.label.place_configure(x=x, y=y)
1540
Serhiy Storchaka9be238d2014-01-07 19:32:58 +02001541 from_ = _to_number(self.scale['from'])
1542 to = _to_number(self.scale['to'])
Guilherme Polocda93aa2009-01-28 13:09:03 +00001543 if to < from_:
1544 from_, to = to, from_
1545 newval = self._variable.get()
1546 if not from_ <= newval <= to:
1547 # value outside range, set value back to the last valid one
1548 self.value = self._last_valid
1549 return
1550
1551 self._last_valid = newval
1552 self.label['text'] = newval
1553 self.after_idle(adjust_label)
1554
1555
1556 def _get_value(self):
1557 """Return current scale value."""
1558 return self._variable.get()
1559
1560
1561 def _set_value(self, val):
1562 """Set new scale value."""
1563 self._variable.set(val)
1564
1565
1566 value = property(_get_value, _set_value)
1567
1568
1569class OptionMenu(Menubutton):
1570 """Themed OptionMenu, based after Tkinter's OptionMenu, which allows
1571 the user to select a value from a menu."""
1572
1573 def __init__(self, master, variable, default=None, *values, **kwargs):
1574 """Construct a themed OptionMenu widget with master as the parent,
1575 the resource textvariable set to variable, the initially selected
1576 value specified by the default parameter, the menu values given by
1577 *values and additional keywords.
1578
1579 WIDGET-SPECIFIC OPTIONS
1580
1581 style: stylename
1582 Menubutton style.
1583 direction: 'above', 'below', 'left', 'right', or 'flush'
1584 Menubutton direction.
1585 command: callback
1586 A callback that will be invoked after selecting an item.
1587 """
1588 kw = {'textvariable': variable, 'style': kwargs.pop('style', None),
1589 'direction': kwargs.pop('direction', None)}
1590 Menubutton.__init__(self, master, **kw)
1591 self['menu'] = Tkinter.Menu(self, tearoff=False)
1592
1593 self._variable = variable
1594 self._callback = kwargs.pop('command', None)
1595 if kwargs:
1596 raise Tkinter.TclError('unknown option -%s' % (
1597 kwargs.iterkeys().next()))
1598
1599 self.set_menu(default, *values)
1600
1601
1602 def __getitem__(self, item):
1603 if item == 'menu':
1604 return self.nametowidget(Menubutton.__getitem__(self, item))
1605
1606 return Menubutton.__getitem__(self, item)
1607
1608
1609 def set_menu(self, default=None, *values):
1610 """Build a new menu of radiobuttons with *values and optionally
1611 a default value."""
1612 menu = self['menu']
1613 menu.delete(0, 'end')
1614 for val in values:
1615 menu.add_radiobutton(label=val,
1616 command=Tkinter._setit(self._variable, val, self._callback))
1617
1618 if default:
1619 self._variable.set(default)
1620
1621
1622 def destroy(self):
1623 """Destroy this widget and its associated variable."""
1624 del self._variable
1625 Menubutton.destroy(self)