blob: 573544dd84a390215d878953af91d8b011790ef4 [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",
Alan D Moorea48e78a2018-02-08 18:03:55 -060022 "Separator", "Sizegrip", "Spinbox", "Style", "Treeview",
Guilherme Polo5f238482009-01-28 14:41:10 +000023 # 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 Storchaka8f0a1d02014-09-06 22:47:58 +030029from tkinter import _flatten, _join, _stringify, _splitdict
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:
Mike53f7a7c2017-12-14 14:04:53 +030084 # hacks for backward compatibility
Serhiy Storchakab1396522013-01-15 17:56:08 +020085 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
Martin Panter69332c12016-08-04 13:07:31 +0000154 layout and ttk::style settings. Note that the layout doesn't have to
Guilherme Polo5f238482009-01-28 14:41:10 +0000155 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
Guilherme Polo5f238482009-01-28 14:41:10 +0000243def _list_from_statespec(stuple):
244 """Construct a list from the given statespec tuple according to the
245 accepted statespec accepted by _format_mapdict."""
246 nval = []
247 for val in stuple:
248 typename = getattr(val, 'typename', None)
249 if typename is None:
250 nval.append(val)
251 else: # this is a Tcl object
252 val = str(val)
253 if typename == 'StateSpec':
254 val = val.split()
255 nval.append(val)
256
257 it = iter(nval)
258 return [_flatten(spec) for spec in zip(it, it)]
259
Serhiy Storchakab49eff22014-05-28 18:38:27 +0300260def _list_from_layouttuple(tk, ltuple):
Guilherme Polo5f238482009-01-28 14:41:10 +0000261 """Construct a list from the tuple returned by ttk::layout, this is
262 somewhat the reverse of _format_layoutlist."""
Serhiy Storchaka8381f902014-06-01 11:21:55 +0300263 ltuple = tk.splitlist(ltuple)
Guilherme Polo5f238482009-01-28 14:41:10 +0000264 res = []
265
266 indx = 0
267 while indx < len(ltuple):
268 name = ltuple[indx]
269 opts = {}
270 res.append((name, opts))
271 indx += 1
272
273 while indx < len(ltuple): # grab name's options
274 opt, val = ltuple[indx:indx + 2]
275 if not opt.startswith('-'): # found next name
276 break
277
278 opt = opt[1:] # remove the '-' from the option
279 indx += 2
280
281 if opt == 'children':
Serhiy Storchakab49eff22014-05-28 18:38:27 +0300282 val = _list_from_layouttuple(tk, val)
Guilherme Polo5f238482009-01-28 14:41:10 +0000283
284 opts[opt] = val
285
286 return res
287
Serhiy Storchakab49eff22014-05-28 18:38:27 +0300288def _val_or_dict(tk, options, *args):
289 """Format options then call Tk command with args and options and return
Guilherme Polo5f238482009-01-28 14:41:10 +0000290 the appropriate result.
291
Martin Panter7462b6492015-11-02 03:37:02 +0000292 If no option is specified, a dict is returned. If an option is
Guilherme Polo5f238482009-01-28 14:41:10 +0000293 specified with the None value, the value for that option is returned.
294 Otherwise, the function just sets the passed options and the caller
295 shouldn't be expecting a return value anyway."""
296 options = _format_optdict(options)
Serhiy Storchakab49eff22014-05-28 18:38:27 +0300297 res = tk.call(*(args + options))
Guilherme Polo5f238482009-01-28 14:41:10 +0000298
299 if len(options) % 2: # option specified without a value, return its value
300 return res
301
Serhiy Storchaka8f0a1d02014-09-06 22:47:58 +0300302 return _splitdict(tk, res, conv=_tclobj_to_py)
Guilherme Polo5f238482009-01-28 14:41:10 +0000303
304def _convert_stringval(value):
305 """Converts a value to, hopefully, a more appropriate Python object."""
306 value = str(value)
307 try:
308 value = int(value)
309 except (ValueError, TypeError):
310 pass
311
312 return value
313
Serhiy Storchakaa21acb52014-01-07 19:27:42 +0200314def _to_number(x):
315 if isinstance(x, str):
316 if '.' in x:
317 x = float(x)
318 else:
319 x = int(x)
320 return x
321
Serhiy Storchaka8f0a1d02014-09-06 22:47:58 +0300322def _tclobj_to_py(val):
323 """Return value converted from Tcl object to Python object."""
324 if val and hasattr(val, '__len__') and not isinstance(val, str):
325 if getattr(val[0], 'typename', None) == 'StateSpec':
326 val = _list_from_statespec(val)
327 else:
328 val = list(map(_convert_stringval, val))
329
330 elif hasattr(val, 'typename'): # some other (single) Tcl object
331 val = _convert_stringval(val)
332
333 return val
334
Guilherme Polo5f238482009-01-28 14:41:10 +0000335def tclobjs_to_py(adict):
336 """Returns adict with its values converted from Tcl objects to Python
337 objects."""
338 for opt, val in adict.items():
Serhiy Storchaka8f0a1d02014-09-06 22:47:58 +0300339 adict[opt] = _tclobj_to_py(val)
Guilherme Polo5f238482009-01-28 14:41:10 +0000340
341 return adict
342
Guilherme Poloa91790a2009-02-09 20:40:42 +0000343def setup_master(master=None):
344 """If master is not None, itself is returned. If master is None,
345 the default master is returned if there is one, otherwise a new
346 master is created and returned.
347
348 If it is not allowed to use the default root and master is None,
349 RuntimeError is raised."""
350 if master is None:
351 if tkinter._support_default_root:
352 master = tkinter._default_root or tkinter.Tk()
353 else:
354 raise RuntimeError(
355 "No master specified and tkinter is "
356 "configured to not support default root")
357 return master
358
Guilherme Polo5f238482009-01-28 14:41:10 +0000359
360class Style(object):
361 """Manipulate style database."""
362
363 _name = "ttk::style"
364
365 def __init__(self, master=None):
Guilherme Poloa91790a2009-02-09 20:40:42 +0000366 master = setup_master(master)
Guilherme Polofa8fba92009-02-07 02:33:47 +0000367
368 if not getattr(master, '_tile_loaded', False):
369 # Load tile now, if needed
370 _load_tile(master)
Guilherme Polo5f238482009-01-28 14:41:10 +0000371
372 self.master = master
373 self.tk = self.master.tk
374
375
376 def configure(self, style, query_opt=None, **kw):
377 """Query or sets the default value of the specified option(s) in
378 style.
379
380 Each key in kw is an option and each value is either a string or
381 a sequence identifying the value for that option."""
382 if query_opt is not None:
383 kw[query_opt] = None
Ethan Furmanad1a3412015-07-21 00:54:19 -0700384 result = _val_or_dict(self.tk, kw, self._name, "configure", style)
385 if result or query_opt:
386 return result
Guilherme Polo5f238482009-01-28 14:41:10 +0000387
388
389 def map(self, style, query_opt=None, **kw):
390 """Query or sets dynamic values of the specified option(s) in
391 style.
392
393 Each key in kw is an option and each value should be a list or a
394 tuple (usually) containing statespecs grouped in tuples, or list,
395 or something else of your preference. A statespec is compound of
396 one or more states and then a value."""
397 if query_opt is not None:
Serhiy Storchakaa21acb52014-01-07 19:27:42 +0200398 return _list_from_statespec(self.tk.splitlist(
399 self.tk.call(self._name, "map", style, '-%s' % query_opt)))
Guilherme Polo5f238482009-01-28 14:41:10 +0000400
Serhiy Storchaka8f0a1d02014-09-06 22:47:58 +0300401 return _splitdict(
402 self.tk,
403 self.tk.call(self._name, "map", style, *_format_mapdict(kw)),
404 conv=_tclobj_to_py)
Guilherme Polo5f238482009-01-28 14:41:10 +0000405
406
407 def lookup(self, style, option, state=None, default=None):
408 """Returns the value specified for option in style.
409
410 If state is specified it is expected to be a sequence of one
411 or more states. If the default argument is set, it is used as
412 a fallback value in case no specification for option is found."""
413 state = ' '.join(state) if state else ''
414
415 return self.tk.call(self._name, "lookup", style, '-%s' % option,
416 state, default)
417
418
419 def layout(self, style, layoutspec=None):
420 """Define the widget layout for given style. If layoutspec is
421 omitted, return the layout specification for given style.
422
423 layoutspec is expected to be a list or an object different than
424 None that evaluates to False if you want to "turn off" that style.
425 If it is a list (or tuple, or something else), each item should be
426 a tuple where the first item is the layout name and the second item
427 should have the format described below:
428
429 LAYOUTS
430
431 A layout can contain the value None, if takes no options, or
432 a dict of options specifying how to arrange the element.
433 The layout mechanism uses a simplified version of the pack
434 geometry manager: given an initial cavity, each element is
435 allocated a parcel. Valid options/values are:
436
437 side: whichside
438 Specifies which side of the cavity to place the
439 element; one of top, right, bottom or left. If
440 omitted, the element occupies the entire cavity.
441
442 sticky: nswe
443 Specifies where the element is placed inside its
444 allocated parcel.
445
446 children: [sublayout... ]
447 Specifies a list of elements to place inside the
448 element. Each element is a tuple (or other sequence)
449 where the first item is the layout name, and the other
450 is a LAYOUT."""
451 lspec = None
452 if layoutspec:
453 lspec = _format_layoutlist(layoutspec)[0]
454 elif layoutspec is not None: # will disable the layout ({}, '', etc)
455 lspec = "null" # could be any other word, but this may make sense
456 # when calling layout(style) later
457
Serhiy Storchaka8381f902014-06-01 11:21:55 +0300458 return _list_from_layouttuple(self.tk,
459 self.tk.call(self._name, "layout", style, lspec))
Guilherme Polo5f238482009-01-28 14:41:10 +0000460
461
462 def element_create(self, elementname, etype, *args, **kw):
463 """Create a new element in the current theme of given etype."""
464 spec, opts = _format_elemcreate(etype, False, *args, **kw)
465 self.tk.call(self._name, "element", "create", elementname, etype,
466 spec, *opts)
467
468
469 def element_names(self):
470 """Returns the list of elements defined in the current theme."""
Ethan Furmanad1a3412015-07-21 00:54:19 -0700471 return tuple(n.lstrip('-') for n in self.tk.splitlist(
472 self.tk.call(self._name, "element", "names")))
Guilherme Polo5f238482009-01-28 14:41:10 +0000473
474
475 def element_options(self, elementname):
476 """Return the list of elementname's options."""
Ethan Furmanad1a3412015-07-21 00:54:19 -0700477 return tuple(o.lstrip('-') for o in self.tk.splitlist(
478 self.tk.call(self._name, "element", "options", elementname)))
Guilherme Polo5f238482009-01-28 14:41:10 +0000479
480
481 def theme_create(self, themename, parent=None, settings=None):
482 """Creates a new theme.
483
484 It is an error if themename already exists. If parent is
485 specified, the new theme will inherit styles, elements and
486 layouts from the specified parent theme. If settings are present,
487 they are expected to have the same syntax used for theme_settings."""
488 script = _script_from_settings(settings) if settings else ''
489
490 if parent:
491 self.tk.call(self._name, "theme", "create", themename,
492 "-parent", parent, "-settings", script)
493 else:
494 self.tk.call(self._name, "theme", "create", themename,
495 "-settings", script)
496
497
498 def theme_settings(self, themename, settings):
499 """Temporarily sets the current theme to themename, apply specified
500 settings and then restore the previous theme.
501
502 Each key in settings is a style and each value may contain the
503 keys 'configure', 'map', 'layout' and 'element create' and they
504 are expected to have the same format as specified by the methods
505 configure, map, layout and element_create respectively."""
506 script = _script_from_settings(settings)
507 self.tk.call(self._name, "theme", "settings", themename, script)
508
509
510 def theme_names(self):
511 """Returns a list of all known themes."""
Serhiy Storchakaa21acb52014-01-07 19:27:42 +0200512 return self.tk.splitlist(self.tk.call(self._name, "theme", "names"))
Guilherme Polo5f238482009-01-28 14:41:10 +0000513
514
515 def theme_use(self, themename=None):
516 """If themename is None, returns the theme in use, otherwise, set
517 the current theme to themename, refreshes all widgets and emits
518 a <<ThemeChanged>> event."""
519 if themename is None:
520 # Starting on Tk 8.6, checking this global is no longer needed
521 # since it allows doing self.tk.call(self._name, "theme", "use")
522 return self.tk.eval("return $ttk::currentTheme")
523
524 # using "ttk::setTheme" instead of "ttk::style theme use" causes
525 # the variable currentTheme to be updated, also, ttk::setTheme calls
526 # "ttk::style theme use" in order to change theme.
527 self.tk.call("ttk::setTheme", themename)
528
529
530class Widget(tkinter.Widget):
531 """Base class for Tk themed widgets."""
532
533 def __init__(self, master, widgetname, kw=None):
534 """Constructs a Ttk Widget with the parent master.
535
536 STANDARD OPTIONS
537
538 class, cursor, takefocus, style
539
540 SCROLLABLE WIDGET OPTIONS
541
542 xscrollcommand, yscrollcommand
543
544 LABEL WIDGET OPTIONS
545
546 text, textvariable, underline, image, compound, width
547
548 WIDGET STATES
549
550 active, disabled, focus, pressed, selected, background,
551 readonly, alternate, invalid
552 """
Guilherme Poloa91790a2009-02-09 20:40:42 +0000553 master = setup_master(master)
Guilherme Polofa8fba92009-02-07 02:33:47 +0000554 if not getattr(master, '_tile_loaded', False):
555 # Load tile now, if needed
556 _load_tile(master)
Guilherme Polo5f238482009-01-28 14:41:10 +0000557 tkinter.Widget.__init__(self, master, widgetname, kw=kw)
558
559
560 def identify(self, x, y):
561 """Returns the name of the element at position x, y, or the empty
562 string if the point does not lie within any element.
563
564 x and y are pixel coordinates relative to the widget."""
565 return self.tk.call(self._w, "identify", x, y)
566
567
568 def instate(self, statespec, callback=None, *args, **kw):
569 """Test the widget's state.
570
571 If callback is not specified, returns True if the widget state
572 matches statespec and False otherwise. If callback is specified,
573 then it will be invoked with *args, **kw if the widget state
574 matches statespec. statespec is expected to be a sequence."""
Serhiy Storchakaa21acb52014-01-07 19:27:42 +0200575 ret = self.tk.getboolean(
576 self.tk.call(self._w, "instate", ' '.join(statespec)))
Guilherme Polo5f238482009-01-28 14:41:10 +0000577 if ret and callback:
578 return callback(*args, **kw)
579
Serhiy Storchaka9a6e2012015-04-04 12:43:01 +0300580 return ret
Guilherme Polo5f238482009-01-28 14:41:10 +0000581
582
583 def state(self, statespec=None):
584 """Modify or inquire widget state.
585
586 Widget state is returned if statespec is None, otherwise it is
587 set according to the statespec flags and then a new state spec
588 is returned indicating which flags were changed. statespec is
589 expected to be a sequence."""
590 if statespec is not None:
591 statespec = ' '.join(statespec)
592
593 return self.tk.splitlist(str(self.tk.call(self._w, "state", statespec)))
594
595
596class Button(Widget):
597 """Ttk Button widget, displays a textual label and/or image, and
598 evaluates a command when pressed."""
599
600 def __init__(self, master=None, **kw):
601 """Construct a Ttk Button widget with the parent master.
602
603 STANDARD OPTIONS
604
605 class, compound, cursor, image, state, style, takefocus,
606 text, textvariable, underline, width
607
608 WIDGET-SPECIFIC OPTIONS
609
610 command, default, width
611 """
612 Widget.__init__(self, master, "ttk::button", kw)
613
614
615 def invoke(self):
616 """Invokes the command associated with the button."""
617 return self.tk.call(self._w, "invoke")
618
619
620class Checkbutton(Widget):
621 """Ttk Checkbutton widget which is either in on- or off-state."""
622
623 def __init__(self, master=None, **kw):
624 """Construct a Ttk Checkbutton widget with the parent master.
625
626 STANDARD OPTIONS
627
628 class, compound, cursor, image, state, style, takefocus,
629 text, textvariable, underline, width
630
631 WIDGET-SPECIFIC OPTIONS
632
633 command, offvalue, onvalue, variable
634 """
635 Widget.__init__(self, master, "ttk::checkbutton", kw)
636
637
638 def invoke(self):
639 """Toggles between the selected and deselected states and
640 invokes the associated command. If the widget is currently
641 selected, sets the option variable to the offvalue option
642 and deselects the widget; otherwise, sets the option variable
643 to the option onvalue.
644
645 Returns the result of the associated command."""
646 return self.tk.call(self._w, "invoke")
647
648
649class Entry(Widget, tkinter.Entry):
650 """Ttk Entry widget displays a one-line text string and allows that
651 string to be edited by the user."""
652
653 def __init__(self, master=None, widget=None, **kw):
654 """Constructs a Ttk Entry widget with the parent master.
655
656 STANDARD OPTIONS
657
658 class, cursor, style, takefocus, xscrollcommand
659
660 WIDGET-SPECIFIC OPTIONS
661
662 exportselection, invalidcommand, justify, show, state,
663 textvariable, validate, validatecommand, width
664
665 VALIDATION MODES
666
667 none, key, focus, focusin, focusout, all
668 """
669 Widget.__init__(self, master, widget or "ttk::entry", kw)
670
671
672 def bbox(self, index):
673 """Return a tuple of (x, y, width, height) which describes the
674 bounding box of the character given by index."""
Serhiy Storchakaa21acb52014-01-07 19:27:42 +0200675 return self._getints(self.tk.call(self._w, "bbox", index))
Guilherme Polo5f238482009-01-28 14:41:10 +0000676
677
678 def identify(self, x, y):
679 """Returns the name of the element at position x, y, or the
680 empty string if the coordinates are outside the window."""
681 return self.tk.call(self._w, "identify", x, y)
682
683
684 def validate(self):
685 """Force revalidation, independent of the conditions specified
686 by the validate option. Returns False if validation fails, True
687 if it succeeds. Sets or clears the invalid state accordingly."""
Serhiy Storchaka9a6e2012015-04-04 12:43:01 +0300688 return self.tk.getboolean(self.tk.call(self._w, "validate"))
Guilherme Polo5f238482009-01-28 14:41:10 +0000689
690
691class Combobox(Entry):
692 """Ttk Combobox widget combines a text field with a pop-down list of
693 values."""
694
695 def __init__(self, master=None, **kw):
696 """Construct a Ttk Combobox widget with the parent master.
697
698 STANDARD OPTIONS
699
700 class, cursor, style, takefocus
701
702 WIDGET-SPECIFIC OPTIONS
703
704 exportselection, justify, height, postcommand, state,
705 textvariable, values, width
706 """
Guilherme Polo5f238482009-01-28 14:41:10 +0000707 Entry.__init__(self, master, "ttk::combobox", **kw)
708
709
Guilherme Polo5f238482009-01-28 14:41:10 +0000710 def current(self, newindex=None):
711 """If newindex is supplied, sets the combobox value to the
712 element at position newindex in the list of values. Otherwise,
713 returns the index of the current value in the list of values
714 or -1 if the current value does not appear in the list."""
Serhiy Storchakaa21acb52014-01-07 19:27:42 +0200715 if newindex is None:
716 return self.tk.getint(self.tk.call(self._w, "current"))
Guilherme Polo5f238482009-01-28 14:41:10 +0000717 return self.tk.call(self._w, "current", newindex)
718
719
720 def set(self, value):
721 """Sets the value of the combobox to value."""
722 self.tk.call(self._w, "set", value)
723
724
725class Frame(Widget):
726 """Ttk Frame widget is a container, used to group other widgets
727 together."""
728
729 def __init__(self, master=None, **kw):
730 """Construct a Ttk Frame with parent master.
731
732 STANDARD OPTIONS
733
734 class, cursor, style, takefocus
735
736 WIDGET-SPECIFIC OPTIONS
737
738 borderwidth, relief, padding, width, height
739 """
740 Widget.__init__(self, master, "ttk::frame", kw)
741
742
743class Label(Widget):
744 """Ttk Label widget displays a textual label and/or image."""
745
746 def __init__(self, master=None, **kw):
747 """Construct a Ttk Label with parent master.
748
749 STANDARD OPTIONS
750
751 class, compound, cursor, image, style, takefocus, text,
752 textvariable, underline, width
753
754 WIDGET-SPECIFIC OPTIONS
755
756 anchor, background, font, foreground, justify, padding,
757 relief, text, wraplength
758 """
759 Widget.__init__(self, master, "ttk::label", kw)
760
761
762class Labelframe(Widget):
763 """Ttk Labelframe widget is a container used to group other widgets
764 together. It has an optional label, which may be a plain text string
765 or another widget."""
766
767 def __init__(self, master=None, **kw):
768 """Construct a Ttk Labelframe with parent master.
769
770 STANDARD OPTIONS
771
772 class, cursor, style, takefocus
773
774 WIDGET-SPECIFIC OPTIONS
775 labelanchor, text, underline, padding, labelwidget, width,
776 height
777 """
778 Widget.__init__(self, master, "ttk::labelframe", kw)
779
780LabelFrame = Labelframe # tkinter name compatibility
781
782
783class Menubutton(Widget):
784 """Ttk Menubutton widget displays a textual label and/or image, and
785 displays a menu when pressed."""
786
787 def __init__(self, master=None, **kw):
788 """Construct a Ttk Menubutton with parent master.
789
790 STANDARD OPTIONS
791
792 class, compound, cursor, image, state, style, takefocus,
793 text, textvariable, underline, width
794
795 WIDGET-SPECIFIC OPTIONS
796
797 direction, menu
798 """
799 Widget.__init__(self, master, "ttk::menubutton", kw)
800
801
802class Notebook(Widget):
803 """Ttk Notebook widget manages a collection of windows and displays
804 a single one at a time. Each child window is associated with a tab,
805 which the user may select to change the currently-displayed window."""
806
807 def __init__(self, master=None, **kw):
808 """Construct a Ttk Notebook with parent master.
809
810 STANDARD OPTIONS
811
812 class, cursor, style, takefocus
813
814 WIDGET-SPECIFIC OPTIONS
815
816 height, padding, width
817
818 TAB OPTIONS
819
820 state, sticky, padding, text, image, compound, underline
821
822 TAB IDENTIFIERS (tab_id)
823
824 The tab_id argument found in several methods may take any of
825 the following forms:
826
827 * An integer between zero and the number of tabs
828 * The name of a child window
829 * A positional specification of the form "@x,y", which
830 defines the tab
831 * The string "current", which identifies the
832 currently-selected tab
833 * The string "end", which returns the number of tabs (only
834 valid for method index)
835 """
836 Widget.__init__(self, master, "ttk::notebook", kw)
837
838
839 def add(self, child, **kw):
840 """Adds a new tab to the notebook.
841
842 If window is currently managed by the notebook but hidden, it is
843 restored to its previous position."""
844 self.tk.call(self._w, "add", child, *(_format_optdict(kw)))
845
846
847 def forget(self, tab_id):
848 """Removes the tab specified by tab_id, unmaps and unmanages the
849 associated window."""
850 self.tk.call(self._w, "forget", tab_id)
851
852
853 def hide(self, tab_id):
854 """Hides the tab specified by tab_id.
855
856 The tab will not be displayed, but the associated window remains
857 managed by the notebook and its configuration remembered. Hidden
858 tabs may be restored with the add command."""
859 self.tk.call(self._w, "hide", tab_id)
860
861
862 def identify(self, x, y):
863 """Returns the name of the tab element at position x, y, or the
864 empty string if none."""
865 return self.tk.call(self._w, "identify", x, y)
866
867
868 def index(self, tab_id):
869 """Returns the numeric index of the tab specified by tab_id, or
870 the total number of tabs if tab_id is the string "end"."""
Serhiy Storchakaa21acb52014-01-07 19:27:42 +0200871 return self.tk.getint(self.tk.call(self._w, "index", tab_id))
Guilherme Polo5f238482009-01-28 14:41:10 +0000872
873
874 def insert(self, pos, child, **kw):
875 """Inserts a pane at the specified position.
876
877 pos is either the string end, an integer index, or the name of
878 a managed child. If child is already managed by the notebook,
879 moves it to the specified position."""
880 self.tk.call(self._w, "insert", pos, child, *(_format_optdict(kw)))
881
882
883 def select(self, tab_id=None):
884 """Selects the specified tab.
885
886 The associated child window will be displayed, and the
887 previously-selected window (if different) is unmapped. If tab_id
888 is omitted, returns the widget name of the currently selected
889 pane."""
890 return self.tk.call(self._w, "select", tab_id)
891
892
893 def tab(self, tab_id, option=None, **kw):
894 """Query or modify the options of the specific tab_id.
895
896 If kw is not given, returns a dict of the tab option values. If option
897 is specified, returns the value of that option. Otherwise, sets the
898 options to the corresponding values."""
899 if option is not None:
900 kw[option] = None
Serhiy Storchakab49eff22014-05-28 18:38:27 +0300901 return _val_or_dict(self.tk, kw, self._w, "tab", tab_id)
Guilherme Polo5f238482009-01-28 14:41:10 +0000902
903
904 def tabs(self):
905 """Returns a list of windows managed by the notebook."""
Serhiy Storchakaa21acb52014-01-07 19:27:42 +0200906 return self.tk.splitlist(self.tk.call(self._w, "tabs") or ())
Guilherme Polo5f238482009-01-28 14:41:10 +0000907
908
909 def enable_traversal(self):
910 """Enable keyboard traversal for a toplevel window containing
911 this notebook.
912
913 This will extend the bindings for the toplevel window containing
914 this notebook as follows:
915
916 Control-Tab: selects the tab following the currently selected
917 one
918
919 Shift-Control-Tab: selects the tab preceding the currently
920 selected one
921
922 Alt-K: where K is the mnemonic (underlined) character of any
923 tab, will select that tab.
924
925 Multiple notebooks in a single toplevel may be enabled for
926 traversal, including nested notebooks. However, notebook traversal
927 only works properly if all panes are direct children of the
928 notebook."""
929 # The only, and good, difference I see is about mnemonics, which works
930 # after calling this method. Control-Tab and Shift-Control-Tab always
931 # works (here at least).
932 self.tk.call("ttk::notebook::enableTraversal", self._w)
933
934
935class Panedwindow(Widget, tkinter.PanedWindow):
936 """Ttk Panedwindow widget displays a number of subwindows, stacked
937 either vertically or horizontally."""
938
939 def __init__(self, master=None, **kw):
940 """Construct a Ttk Panedwindow with parent master.
941
942 STANDARD OPTIONS
943
944 class, cursor, style, takefocus
945
946 WIDGET-SPECIFIC OPTIONS
947
948 orient, width, height
949
950 PANE OPTIONS
951
952 weight
953 """
954 Widget.__init__(self, master, "ttk::panedwindow", kw)
955
956
957 forget = tkinter.PanedWindow.forget # overrides Pack.forget
958
959
960 def insert(self, pos, child, **kw):
961 """Inserts a pane at the specified positions.
962
963 pos is either the string end, and integer index, or the name
964 of a child. If child is already managed by the paned window,
965 moves it to the specified position."""
966 self.tk.call(self._w, "insert", pos, child, *(_format_optdict(kw)))
967
968
969 def pane(self, pane, option=None, **kw):
970 """Query or modify the options of the specified pane.
971
972 pane is either an integer index or the name of a managed subwindow.
973 If kw is not given, returns a dict of the pane option values. If
974 option is specified then the value for that option is returned.
Ezio Melotti42da6632011-03-15 05:18:48 +0200975 Otherwise, sets the options to the corresponding values."""
Guilherme Polo5f238482009-01-28 14:41:10 +0000976 if option is not None:
977 kw[option] = None
Serhiy Storchakab49eff22014-05-28 18:38:27 +0300978 return _val_or_dict(self.tk, kw, self._w, "pane", pane)
Guilherme Polo5f238482009-01-28 14:41:10 +0000979
980
981 def sashpos(self, index, newpos=None):
982 """If newpos is specified, sets the position of sash number index.
983
984 May adjust the positions of adjacent sashes to ensure that
985 positions are monotonically increasing. Sash positions are further
986 constrained to be between 0 and the total size of the widget.
987
988 Returns the new position of sash number index."""
Serhiy Storchakaa21acb52014-01-07 19:27:42 +0200989 return self.tk.getint(self.tk.call(self._w, "sashpos", index, newpos))
Guilherme Polo5f238482009-01-28 14:41:10 +0000990
991PanedWindow = Panedwindow # tkinter name compatibility
992
993
994class Progressbar(Widget):
995 """Ttk Progressbar widget shows the status of a long-running
996 operation. They can operate in two modes: determinate mode shows the
997 amount completed relative to the total amount of work to be done, and
998 indeterminate mode provides an animated display to let the user know
999 that something is happening."""
1000
1001 def __init__(self, master=None, **kw):
1002 """Construct a Ttk Progressbar with parent master.
1003
1004 STANDARD OPTIONS
1005
1006 class, cursor, style, takefocus
1007
1008 WIDGET-SPECIFIC OPTIONS
1009
1010 orient, length, mode, maximum, value, variable, phase
1011 """
1012 Widget.__init__(self, master, "ttk::progressbar", kw)
1013
1014
1015 def start(self, interval=None):
1016 """Begin autoincrement mode: schedules a recurring timer event
1017 that calls method step every interval milliseconds.
1018
Martin Panter46f50722016-05-26 05:35:26 +00001019 interval defaults to 50 milliseconds (20 steps/second) if omitted."""
Guilherme Polo5f238482009-01-28 14:41:10 +00001020 self.tk.call(self._w, "start", interval)
1021
1022
1023 def step(self, amount=None):
1024 """Increments the value option by amount.
1025
1026 amount defaults to 1.0 if omitted."""
1027 self.tk.call(self._w, "step", amount)
1028
1029
1030 def stop(self):
1031 """Stop autoincrement mode: cancels any recurring timer event
1032 initiated by start."""
1033 self.tk.call(self._w, "stop")
1034
1035
1036class Radiobutton(Widget):
1037 """Ttk Radiobutton widgets are used in groups to show or change a
1038 set of mutually-exclusive options."""
1039
1040 def __init__(self, master=None, **kw):
1041 """Construct a Ttk Radiobutton with parent master.
1042
1043 STANDARD OPTIONS
1044
1045 class, compound, cursor, image, state, style, takefocus,
1046 text, textvariable, underline, width
1047
1048 WIDGET-SPECIFIC OPTIONS
1049
1050 command, value, variable
1051 """
1052 Widget.__init__(self, master, "ttk::radiobutton", kw)
1053
1054
1055 def invoke(self):
1056 """Sets the option variable to the option value, selects the
1057 widget, and invokes the associated command.
1058
1059 Returns the result of the command, or an empty string if
1060 no command is specified."""
1061 return self.tk.call(self._w, "invoke")
1062
1063
1064class Scale(Widget, tkinter.Scale):
1065 """Ttk Scale widget is typically used to control the numeric value of
1066 a linked variable that varies uniformly over some range."""
1067
1068 def __init__(self, master=None, **kw):
1069 """Construct a Ttk Scale with parent master.
1070
1071 STANDARD OPTIONS
1072
1073 class, cursor, style, takefocus
1074
1075 WIDGET-SPECIFIC OPTIONS
1076
1077 command, from, length, orient, to, value, variable
1078 """
1079 Widget.__init__(self, master, "ttk::scale", kw)
1080
1081
1082 def configure(self, cnf=None, **kw):
1083 """Modify or query scale options.
1084
1085 Setting a value for any of the "from", "from_" or "to" options
1086 generates a <<RangeChanged>> event."""
1087 if cnf:
1088 kw.update(cnf)
1089 Widget.configure(self, **kw)
1090 if any(['from' in kw, 'from_' in kw, 'to' in kw]):
1091 self.event_generate('<<RangeChanged>>')
1092
1093
1094 def get(self, x=None, y=None):
1095 """Get the current value of the value option, or the value
1096 corresponding to the coordinates x, y if they are specified.
1097
1098 x and y are pixel coordinates relative to the scale widget
1099 origin."""
1100 return self.tk.call(self._w, 'get', x, y)
1101
1102
1103class Scrollbar(Widget, tkinter.Scrollbar):
1104 """Ttk Scrollbar controls the viewport of a scrollable widget."""
1105
1106 def __init__(self, master=None, **kw):
1107 """Construct a Ttk Scrollbar with parent master.
1108
1109 STANDARD OPTIONS
1110
1111 class, cursor, style, takefocus
1112
1113 WIDGET-SPECIFIC OPTIONS
1114
1115 command, orient
1116 """
1117 Widget.__init__(self, master, "ttk::scrollbar", kw)
1118
1119
1120class Separator(Widget):
1121 """Ttk Separator widget displays a horizontal or vertical separator
1122 bar."""
1123
1124 def __init__(self, master=None, **kw):
1125 """Construct a Ttk Separator with parent master.
1126
1127 STANDARD OPTIONS
1128
1129 class, cursor, style, takefocus
1130
1131 WIDGET-SPECIFIC OPTIONS
1132
1133 orient
1134 """
1135 Widget.__init__(self, master, "ttk::separator", kw)
1136
1137
1138class Sizegrip(Widget):
1139 """Ttk Sizegrip allows the user to resize the containing toplevel
1140 window by pressing and dragging the grip."""
1141
1142 def __init__(self, master=None, **kw):
1143 """Construct a Ttk Sizegrip with parent master.
1144
1145 STANDARD OPTIONS
1146
1147 class, cursor, state, style, takefocus
1148 """
1149 Widget.__init__(self, master, "ttk::sizegrip", kw)
1150
1151
Alan D Moorea48e78a2018-02-08 18:03:55 -06001152class Spinbox(Entry):
1153 """Ttk Spinbox is an Entry with increment and decrement arrows
1154
1155 It is commonly used for number entry or to select from a list of
1156 string values.
1157 """
1158
1159 def __init__(self, master=None, **kw):
1160 """Construct a Ttk Spinbox widget with the parent master.
1161
1162 STANDARD OPTIONS
1163
1164 class, cursor, style, takefocus, validate,
1165 validatecommand, xscrollcommand, invalidcommand
1166
1167 WIDGET-SPECIFIC OPTIONS
1168
1169 to, from_, increment, values, wrap, format, command
1170 """
1171 Entry.__init__(self, master, "ttk::spinbox", **kw)
1172
1173
1174 def set(self, value):
1175 """Sets the value of the Spinbox to value."""
1176 self.tk.call(self._w, "set", value)
1177
1178
Guilherme Polo1fff0082009-08-14 15:05:30 +00001179class Treeview(Widget, tkinter.XView, tkinter.YView):
Guilherme Polo5f238482009-01-28 14:41:10 +00001180 """Ttk Treeview widget displays a hierarchical collection of items.
1181
1182 Each item has a textual label, an optional image, and an optional list
1183 of data values. The data values are displayed in successive columns
1184 after the tree label."""
1185
1186 def __init__(self, master=None, **kw):
1187 """Construct a Ttk Treeview with parent master.
1188
1189 STANDARD OPTIONS
1190
1191 class, cursor, style, takefocus, xscrollcommand,
1192 yscrollcommand
1193
1194 WIDGET-SPECIFIC OPTIONS
1195
1196 columns, displaycolumns, height, padding, selectmode, show
1197
1198 ITEM OPTIONS
1199
1200 text, image, values, open, tags
1201
1202 TAG OPTIONS
1203
1204 foreground, background, font, image
1205 """
1206 Widget.__init__(self, master, "ttk::treeview", kw)
1207
1208
1209 def bbox(self, item, column=None):
1210 """Returns the bounding box (relative to the treeview widget's
1211 window) of the specified item in the form x y width height.
1212
1213 If column is specified, returns the bounding box of that cell.
1214 If the item is not visible (i.e., if it is a descendant of a
1215 closed item or is scrolled offscreen), returns an empty string."""
Serhiy Storchakaa21acb52014-01-07 19:27:42 +02001216 return self._getints(self.tk.call(self._w, "bbox", item, column)) or ''
Guilherme Polo5f238482009-01-28 14:41:10 +00001217
1218
1219 def get_children(self, item=None):
1220 """Returns a tuple of children belonging to item.
1221
1222 If item is not specified, returns root children."""
Serhiy Storchakaa21acb52014-01-07 19:27:42 +02001223 return self.tk.splitlist(
1224 self.tk.call(self._w, "children", item or '') or ())
Guilherme Polo5f238482009-01-28 14:41:10 +00001225
1226
1227 def set_children(self, item, *newchildren):
1228 """Replaces item's child with newchildren.
1229
1230 Children present in item that are not present in newchildren
1231 are detached from tree. No items in newchildren may be an
1232 ancestor of item."""
1233 self.tk.call(self._w, "children", item, newchildren)
1234
1235
1236 def column(self, column, option=None, **kw):
1237 """Query or modify the options for the specified column.
1238
1239 If kw is not given, returns a dict of the column option values. If
1240 option is specified then the value for that option is returned.
1241 Otherwise, sets the options to the corresponding values."""
1242 if option is not None:
1243 kw[option] = None
Serhiy Storchakab49eff22014-05-28 18:38:27 +03001244 return _val_or_dict(self.tk, kw, self._w, "column", column)
Guilherme Polo5f238482009-01-28 14:41:10 +00001245
1246
1247 def delete(self, *items):
1248 """Delete all specified items and all their descendants. The root
1249 item may not be deleted."""
1250 self.tk.call(self._w, "delete", items)
1251
1252
1253 def detach(self, *items):
1254 """Unlinks all of the specified items from the tree.
1255
1256 The items and all of their descendants are still present, and may
1257 be reinserted at another point in the tree, but will not be
1258 displayed. The root item may not be detached."""
1259 self.tk.call(self._w, "detach", items)
1260
1261
1262 def exists(self, item):
Georg Brandlb6046302012-04-04 20:17:06 +02001263 """Returns True if the specified item is present in the tree,
Guilherme Polo5f238482009-01-28 14:41:10 +00001264 False otherwise."""
Serhiy Storchaka9a6e2012015-04-04 12:43:01 +03001265 return self.tk.getboolean(self.tk.call(self._w, "exists", item))
Guilherme Polo5f238482009-01-28 14:41:10 +00001266
1267
1268 def focus(self, item=None):
1269 """If item is specified, sets the focus item to item. Otherwise,
1270 returns the current focus item, or '' if there is none."""
1271 return self.tk.call(self._w, "focus", item)
1272
1273
1274 def heading(self, column, option=None, **kw):
1275 """Query or modify the heading options for the specified column.
1276
1277 If kw is not given, returns a dict of the heading option values. If
1278 option is specified then the value for that option is returned.
1279 Otherwise, sets the options to the corresponding values.
1280
1281 Valid options/values are:
1282 text: text
1283 The text to display in the column heading
1284 image: image_name
1285 Specifies an image to display to the right of the column
1286 heading
1287 anchor: anchor
1288 Specifies how the heading text should be aligned. One of
1289 the standard Tk anchor values
1290 command: callback
1291 A callback to be invoked when the heading label is
1292 pressed.
1293
1294 To configure the tree column heading, call this with column = "#0" """
1295 cmd = kw.get('command')
1296 if cmd and not isinstance(cmd, str):
1297 # callback not registered yet, do it now
1298 kw['command'] = self.master.register(cmd, self._substitute)
1299
1300 if option is not None:
1301 kw[option] = None
1302
Serhiy Storchakab49eff22014-05-28 18:38:27 +03001303 return _val_or_dict(self.tk, kw, self._w, 'heading', column)
Guilherme Polo5f238482009-01-28 14:41:10 +00001304
1305
1306 def identify(self, component, x, y):
1307 """Returns a description of the specified component under the
1308 point given by x and y, or the empty string if no such component
1309 is present at that position."""
1310 return self.tk.call(self._w, "identify", component, x, y)
1311
1312
1313 def identify_row(self, y):
1314 """Returns the item ID of the item at position y."""
1315 return self.identify("row", 0, y)
1316
1317
1318 def identify_column(self, x):
1319 """Returns the data column identifier of the cell at position x.
1320
1321 The tree column has ID #0."""
1322 return self.identify("column", x, 0)
1323
1324
1325 def identify_region(self, x, y):
1326 """Returns one of:
1327
1328 heading: Tree heading area.
1329 separator: Space between two columns headings;
1330 tree: The tree area.
1331 cell: A data cell.
1332
1333 * Availability: Tk 8.6"""
1334 return self.identify("region", x, y)
1335
1336
1337 def identify_element(self, x, y):
1338 """Returns the element at position x, y.
1339
1340 * Availability: Tk 8.6"""
1341 return self.identify("element", x, y)
1342
1343
1344 def index(self, item):
1345 """Returns the integer index of item within its parent's list
1346 of children."""
Serhiy Storchakaa21acb52014-01-07 19:27:42 +02001347 return self.tk.getint(self.tk.call(self._w, "index", item))
Guilherme Polo5f238482009-01-28 14:41:10 +00001348
1349
1350 def insert(self, parent, index, iid=None, **kw):
1351 """Creates a new item and return the item identifier of the newly
1352 created item.
1353
1354 parent is the item ID of the parent item, or the empty string
1355 to create a new top-level item. index is an integer, or the value
1356 end, specifying where in the list of parent's children to insert
1357 the new item. If index is less than or equal to zero, the new node
1358 is inserted at the beginning, if index is greater than or equal to
1359 the current number of children, it is inserted at the end. If iid
1360 is specified, it is used as the item identifier, iid must not
1361 already exist in the tree. Otherwise, a new unique identifier
1362 is generated."""
1363 opts = _format_optdict(kw)
Garvit Khatri3ab44c02018-03-26 12:32:05 +05301364 if iid is not None:
Guilherme Polo5f238482009-01-28 14:41:10 +00001365 res = self.tk.call(self._w, "insert", parent, index,
1366 "-id", iid, *opts)
1367 else:
1368 res = self.tk.call(self._w, "insert", parent, index, *opts)
1369
1370 return res
1371
1372
1373 def item(self, item, option=None, **kw):
1374 """Query or modify the options for the specified item.
1375
1376 If no options are given, a dict with options/values for the item
1377 is returned. If option is specified then the value for that option
1378 is returned. Otherwise, sets the options to the corresponding
1379 values as given by kw."""
1380 if option is not None:
1381 kw[option] = None
Serhiy Storchakab49eff22014-05-28 18:38:27 +03001382 return _val_or_dict(self.tk, kw, self._w, "item", item)
Guilherme Polo5f238482009-01-28 14:41:10 +00001383
1384
1385 def move(self, item, parent, index):
1386 """Moves item to position index in parent's list of children.
1387
1388 It is illegal to move an item under one of its descendants. If
1389 index is less than or equal to zero, item is moved to the
1390 beginning, if greater than or equal to the number of children,
1391 it is moved to the end. If item was detached it is reattached."""
1392 self.tk.call(self._w, "move", item, parent, index)
1393
1394 reattach = move # A sensible method name for reattaching detached items
1395
1396
1397 def next(self, item):
1398 """Returns the identifier of item's next sibling, or '' if item
1399 is the last child of its parent."""
1400 return self.tk.call(self._w, "next", item)
1401
1402
1403 def parent(self, item):
1404 """Returns the ID of the parent of item, or '' if item is at the
1405 top level of the hierarchy."""
1406 return self.tk.call(self._w, "parent", item)
1407
1408
1409 def prev(self, item):
1410 """Returns the identifier of item's previous sibling, or '' if
1411 item is the first child of its parent."""
1412 return self.tk.call(self._w, "prev", item)
1413
1414
1415 def see(self, item):
1416 """Ensure that item is visible.
1417
1418 Sets all of item's ancestors open option to True, and scrolls
1419 the widget if necessary so that item is within the visible
1420 portion of the tree."""
1421 self.tk.call(self._w, "see", item)
1422
1423
Serhiy Storchaka97f1ca12018-02-01 18:49:21 +02001424 def selection(self):
Serhiy Storchakab84f0292016-06-20 00:05:40 +03001425 """Returns the tuple of selected items."""
Serhiy Storchaka97f1ca12018-02-01 18:49:21 +02001426 return self.tk.splitlist(self.tk.call(self._w, "selection"))
Guilherme Polo5f238482009-01-28 14:41:10 +00001427
1428
Serhiy Storchakab84f0292016-06-20 00:05:40 +03001429 def _selection(self, selop, items):
1430 if len(items) == 1 and isinstance(items[0], (tuple, list)):
1431 items = items[0]
1432
1433 self.tk.call(self._w, "selection", selop, items)
Guilherme Polo5f238482009-01-28 14:41:10 +00001434
1435
Serhiy Storchakab84f0292016-06-20 00:05:40 +03001436 def selection_set(self, *items):
1437 """The specified items becomes the new selection."""
1438 self._selection("set", items)
Guilherme Polo5f238482009-01-28 14:41:10 +00001439
1440
Serhiy Storchakab84f0292016-06-20 00:05:40 +03001441 def selection_add(self, *items):
1442 """Add all of the specified items to the selection."""
1443 self._selection("add", items)
Guilherme Polo5f238482009-01-28 14:41:10 +00001444
1445
Serhiy Storchakab84f0292016-06-20 00:05:40 +03001446 def selection_remove(self, *items):
1447 """Remove all of the specified items from the selection."""
1448 self._selection("remove", items)
1449
1450
1451 def selection_toggle(self, *items):
1452 """Toggle the selection state of each specified item."""
1453 self._selection("toggle", items)
Guilherme Polo5f238482009-01-28 14:41:10 +00001454
1455
1456 def set(self, item, column=None, value=None):
Serhiy Storchaka8f0a1d02014-09-06 22:47:58 +03001457 """Query or set the value of given item.
1458
1459 With one argument, return a dictionary of column/value pairs
1460 for the specified item. With two arguments, return the current
1461 value of the specified column. With three arguments, set the
Guilherme Polo5f238482009-01-28 14:41:10 +00001462 value of given column in given item to the specified value."""
1463 res = self.tk.call(self._w, "set", item, column, value)
1464 if column is None and value is None:
Serhiy Storchaka8f0a1d02014-09-06 22:47:58 +03001465 return _splitdict(self.tk, res,
1466 cut_minus=False, conv=_tclobj_to_py)
Guilherme Polo5f238482009-01-28 14:41:10 +00001467 else:
1468 return res
1469
1470
1471 def tag_bind(self, tagname, sequence=None, callback=None):
1472 """Bind a callback for the given event sequence to the tag tagname.
1473 When an event is delivered to an item, the callbacks for each
1474 of the item's tags option are called."""
1475 self._bind((self._w, "tag", "bind", tagname), sequence, callback, add=0)
1476
1477
1478 def tag_configure(self, tagname, option=None, **kw):
1479 """Query or modify the options for the specified tagname.
1480
1481 If kw is not given, returns a dict of the option settings for tagname.
1482 If option is specified, returns the value for that option for the
1483 specified tagname. Otherwise, sets the options to the corresponding
1484 values for the given tagname."""
1485 if option is not None:
1486 kw[option] = None
Serhiy Storchakab49eff22014-05-28 18:38:27 +03001487 return _val_or_dict(self.tk, kw, self._w, "tag", "configure",
Guilherme Polo5f238482009-01-28 14:41:10 +00001488 tagname)
1489
1490
1491 def tag_has(self, tagname, item=None):
1492 """If item is specified, returns 1 or 0 depending on whether the
1493 specified item has the given tagname. Otherwise, returns a list of
1494 all items which have the specified tag.
1495
1496 * Availability: Tk 8.6"""
Serhiy Storchaka8e92f572014-11-07 12:02:31 +02001497 if item is None:
1498 return self.tk.splitlist(
1499 self.tk.call(self._w, "tag", "has", tagname))
1500 else:
1501 return self.tk.getboolean(
Serhiy Storchakaa21acb52014-01-07 19:27:42 +02001502 self.tk.call(self._w, "tag", "has", tagname, item))
Guilherme Polo5f238482009-01-28 14:41:10 +00001503
1504
Guilherme Polo5f238482009-01-28 14:41:10 +00001505# Extensions
1506
1507class LabeledScale(Frame):
1508 """A Ttk Scale widget with a Ttk Label widget indicating its
1509 current value.
1510
1511 The Ttk Scale can be accessed through instance.scale, and Ttk Label
1512 can be accessed through instance.label"""
1513
1514 def __init__(self, master=None, variable=None, from_=0, to=10, **kw):
Serhiy Storchaka6a7b3a72016-04-17 08:32:47 +03001515 """Construct a horizontal LabeledScale with parent master, a
Guilherme Polo5f238482009-01-28 14:41:10 +00001516 variable to be associated with the Ttk Scale widget and its range.
1517 If variable is not specified, a tkinter.IntVar is created.
1518
1519 WIDGET-SPECIFIC OPTIONS
1520
1521 compound: 'top' or 'bottom'
1522 Specifies how to display the label relative to the scale.
1523 Defaults to 'top'.
1524 """
1525 self._label_top = kw.pop('compound', 'top') == 'top'
1526
1527 Frame.__init__(self, master, **kw)
1528 self._variable = variable or tkinter.IntVar(master)
1529 self._variable.set(from_)
1530 self._last_valid = from_
1531
1532 self.label = Label(self)
1533 self.scale = Scale(self, variable=self._variable, from_=from_, to=to)
1534 self.scale.bind('<<RangeChanged>>', self._adjust)
1535
1536 # position scale and label according to the compound option
1537 scale_side = 'bottom' if self._label_top else 'top'
1538 label_side = 'top' if scale_side == 'bottom' else 'bottom'
1539 self.scale.pack(side=scale_side, fill='x')
1540 tmp = Label(self).pack(side=label_side) # place holder
1541 self.label.place(anchor='n' if label_side == 'top' else 's')
1542
1543 # update the label as scale or variable changes
1544 self.__tracecb = self._variable.trace_variable('w', self._adjust)
1545 self.bind('<Configure>', self._adjust)
1546 self.bind('<Map>', self._adjust)
1547
1548
1549 def destroy(self):
1550 """Destroy this widget and possibly its associated variable."""
1551 try:
1552 self._variable.trace_vdelete('w', self.__tracecb)
1553 except AttributeError:
Guilherme Polo5f238482009-01-28 14:41:10 +00001554 pass
1555 else:
1556 del self._variable
Victor Stinnercd7e9c12017-08-08 19:41:21 +02001557 super().destroy()
1558 self.label = None
1559 self.scale = None
Guilherme Polo5f238482009-01-28 14:41:10 +00001560
1561
1562 def _adjust(self, *args):
1563 """Adjust the label position according to the scale."""
1564 def adjust_label():
1565 self.update_idletasks() # "force" scale redraw
1566
1567 x, y = self.scale.coords()
1568 if self._label_top:
1569 y = self.scale.winfo_y() - self.label.winfo_reqheight()
1570 else:
1571 y = self.scale.winfo_reqheight() + self.label.winfo_reqheight()
1572
1573 self.label.place_configure(x=x, y=y)
1574
Serhiy Storchakaa21acb52014-01-07 19:27:42 +02001575 from_ = _to_number(self.scale['from'])
1576 to = _to_number(self.scale['to'])
Guilherme Polo5f238482009-01-28 14:41:10 +00001577 if to < from_:
1578 from_, to = to, from_
1579 newval = self._variable.get()
1580 if not from_ <= newval <= to:
1581 # value outside range, set value back to the last valid one
1582 self.value = self._last_valid
1583 return
1584
1585 self._last_valid = newval
1586 self.label['text'] = newval
1587 self.after_idle(adjust_label)
1588
Serhiy Storchakabdf6b912017-03-19 08:40:32 +02001589 @property
1590 def value(self):
Guilherme Polo5f238482009-01-28 14:41:10 +00001591 """Return current scale value."""
1592 return self._variable.get()
1593
Serhiy Storchakabdf6b912017-03-19 08:40:32 +02001594 @value.setter
1595 def value(self, val):
Guilherme Polo5f238482009-01-28 14:41:10 +00001596 """Set new scale value."""
1597 self._variable.set(val)
1598
1599
Guilherme Polo5f238482009-01-28 14:41:10 +00001600class OptionMenu(Menubutton):
1601 """Themed OptionMenu, based after tkinter's OptionMenu, which allows
1602 the user to select a value from a menu."""
1603
1604 def __init__(self, master, variable, default=None, *values, **kwargs):
1605 """Construct a themed OptionMenu widget with master as the parent,
1606 the resource textvariable set to variable, the initially selected
1607 value specified by the default parameter, the menu values given by
1608 *values and additional keywords.
1609
1610 WIDGET-SPECIFIC OPTIONS
1611
1612 style: stylename
1613 Menubutton style.
1614 direction: 'above', 'below', 'left', 'right', or 'flush'
1615 Menubutton direction.
1616 command: callback
1617 A callback that will be invoked after selecting an item.
1618 """
1619 kw = {'textvariable': variable, 'style': kwargs.pop('style', None),
1620 'direction': kwargs.pop('direction', None)}
1621 Menubutton.__init__(self, master, **kw)
1622 self['menu'] = tkinter.Menu(self, tearoff=False)
1623
1624 self._variable = variable
1625 self._callback = kwargs.pop('command', None)
1626 if kwargs:
1627 raise tkinter.TclError('unknown option -%s' % (
1628 next(iter(kwargs.keys()))))
1629
1630 self.set_menu(default, *values)
1631
1632
1633 def __getitem__(self, item):
1634 if item == 'menu':
1635 return self.nametowidget(Menubutton.__getitem__(self, item))
1636
1637 return Menubutton.__getitem__(self, item)
1638
1639
1640 def set_menu(self, default=None, *values):
1641 """Build a new menu of radiobuttons with *values and optionally
1642 a default value."""
1643 menu = self['menu']
1644 menu.delete(0, 'end')
1645 for val in values:
1646 menu.add_radiobutton(label=val,
csabellaa568e522017-07-31 05:30:09 -04001647 command=tkinter._setit(self._variable, val, self._callback),
1648 variable=self._variable)
Guilherme Polo5f238482009-01-28 14:41:10 +00001649
1650 if default:
1651 self._variable.set(default)
1652
1653
1654 def destroy(self):
1655 """Destroy this widget and its associated variable."""
Victor Stinnercd7e9c12017-08-08 19:41:21 +02001656 try:
1657 del self._variable
1658 except AttributeError:
1659 pass
1660 super().destroy()