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