blob: c7c71cd5a559cf610c50bfac57457cfedac770c5 [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."""
Terry Jan Reedy5ea7bb22020-01-05 11:23:58 -05001087 retval = Widget.configure(self, cnf, **kw)
1088 if not isinstance(cnf, (type(None), str)):
Guilherme Polo5f238482009-01-28 14:41:10 +00001089 kw.update(cnf)
Guilherme Polo5f238482009-01-28 14:41:10 +00001090 if any(['from' in kw, 'from_' in kw, 'to' in kw]):
1091 self.event_generate('<<RangeChanged>>')
Terry Jan Reedy5ea7bb22020-01-05 11:23:58 -05001092 return retval
Guilherme Polo5f238482009-01-28 14:41:10 +00001093
1094
1095 def get(self, x=None, y=None):
1096 """Get the current value of the value option, or the value
1097 corresponding to the coordinates x, y if they are specified.
1098
1099 x and y are pixel coordinates relative to the scale widget
1100 origin."""
1101 return self.tk.call(self._w, 'get', x, y)
1102
1103
1104class Scrollbar(Widget, tkinter.Scrollbar):
1105 """Ttk Scrollbar controls the viewport of a scrollable widget."""
1106
1107 def __init__(self, master=None, **kw):
1108 """Construct a Ttk Scrollbar with parent master.
1109
1110 STANDARD OPTIONS
1111
1112 class, cursor, style, takefocus
1113
1114 WIDGET-SPECIFIC OPTIONS
1115
1116 command, orient
1117 """
1118 Widget.__init__(self, master, "ttk::scrollbar", kw)
1119
1120
1121class Separator(Widget):
1122 """Ttk Separator widget displays a horizontal or vertical separator
1123 bar."""
1124
1125 def __init__(self, master=None, **kw):
1126 """Construct a Ttk Separator with parent master.
1127
1128 STANDARD OPTIONS
1129
1130 class, cursor, style, takefocus
1131
1132 WIDGET-SPECIFIC OPTIONS
1133
1134 orient
1135 """
1136 Widget.__init__(self, master, "ttk::separator", kw)
1137
1138
1139class Sizegrip(Widget):
1140 """Ttk Sizegrip allows the user to resize the containing toplevel
1141 window by pressing and dragging the grip."""
1142
1143 def __init__(self, master=None, **kw):
1144 """Construct a Ttk Sizegrip with parent master.
1145
1146 STANDARD OPTIONS
1147
1148 class, cursor, state, style, takefocus
1149 """
1150 Widget.__init__(self, master, "ttk::sizegrip", kw)
1151
1152
Alan D Moorea48e78a2018-02-08 18:03:55 -06001153class Spinbox(Entry):
1154 """Ttk Spinbox is an Entry with increment and decrement arrows
1155
1156 It is commonly used for number entry or to select from a list of
1157 string values.
1158 """
1159
1160 def __init__(self, master=None, **kw):
1161 """Construct a Ttk Spinbox widget with the parent master.
1162
1163 STANDARD OPTIONS
1164
1165 class, cursor, style, takefocus, validate,
1166 validatecommand, xscrollcommand, invalidcommand
1167
1168 WIDGET-SPECIFIC OPTIONS
1169
1170 to, from_, increment, values, wrap, format, command
1171 """
1172 Entry.__init__(self, master, "ttk::spinbox", **kw)
1173
1174
1175 def set(self, value):
1176 """Sets the value of the Spinbox to value."""
1177 self.tk.call(self._w, "set", value)
1178
1179
Guilherme Polo1fff0082009-08-14 15:05:30 +00001180class Treeview(Widget, tkinter.XView, tkinter.YView):
Guilherme Polo5f238482009-01-28 14:41:10 +00001181 """Ttk Treeview widget displays a hierarchical collection of items.
1182
1183 Each item has a textual label, an optional image, and an optional list
1184 of data values. The data values are displayed in successive columns
1185 after the tree label."""
1186
1187 def __init__(self, master=None, **kw):
1188 """Construct a Ttk Treeview with parent master.
1189
1190 STANDARD OPTIONS
1191
1192 class, cursor, style, takefocus, xscrollcommand,
1193 yscrollcommand
1194
1195 WIDGET-SPECIFIC OPTIONS
1196
1197 columns, displaycolumns, height, padding, selectmode, show
1198
1199 ITEM OPTIONS
1200
1201 text, image, values, open, tags
1202
1203 TAG OPTIONS
1204
1205 foreground, background, font, image
1206 """
1207 Widget.__init__(self, master, "ttk::treeview", kw)
1208
1209
1210 def bbox(self, item, column=None):
1211 """Returns the bounding box (relative to the treeview widget's
1212 window) of the specified item in the form x y width height.
1213
1214 If column is specified, returns the bounding box of that cell.
1215 If the item is not visible (i.e., if it is a descendant of a
1216 closed item or is scrolled offscreen), returns an empty string."""
Serhiy Storchakaa21acb52014-01-07 19:27:42 +02001217 return self._getints(self.tk.call(self._w, "bbox", item, column)) or ''
Guilherme Polo5f238482009-01-28 14:41:10 +00001218
1219
1220 def get_children(self, item=None):
1221 """Returns a tuple of children belonging to item.
1222
1223 If item is not specified, returns root children."""
Serhiy Storchakaa21acb52014-01-07 19:27:42 +02001224 return self.tk.splitlist(
1225 self.tk.call(self._w, "children", item or '') or ())
Guilherme Polo5f238482009-01-28 14:41:10 +00001226
1227
1228 def set_children(self, item, *newchildren):
1229 """Replaces item's child with newchildren.
1230
1231 Children present in item that are not present in newchildren
1232 are detached from tree. No items in newchildren may be an
1233 ancestor of item."""
1234 self.tk.call(self._w, "children", item, newchildren)
1235
1236
1237 def column(self, column, option=None, **kw):
1238 """Query or modify the options for the specified column.
1239
1240 If kw is not given, returns a dict of the column option values. If
1241 option is specified then the value for that option is returned.
1242 Otherwise, sets the options to the corresponding values."""
1243 if option is not None:
1244 kw[option] = None
Serhiy Storchakab49eff22014-05-28 18:38:27 +03001245 return _val_or_dict(self.tk, kw, self._w, "column", column)
Guilherme Polo5f238482009-01-28 14:41:10 +00001246
1247
1248 def delete(self, *items):
1249 """Delete all specified items and all their descendants. The root
1250 item may not be deleted."""
1251 self.tk.call(self._w, "delete", items)
1252
1253
1254 def detach(self, *items):
1255 """Unlinks all of the specified items from the tree.
1256
1257 The items and all of their descendants are still present, and may
1258 be reinserted at another point in the tree, but will not be
1259 displayed. The root item may not be detached."""
1260 self.tk.call(self._w, "detach", items)
1261
1262
1263 def exists(self, item):
Georg Brandlb6046302012-04-04 20:17:06 +02001264 """Returns True if the specified item is present in the tree,
Guilherme Polo5f238482009-01-28 14:41:10 +00001265 False otherwise."""
Serhiy Storchaka9a6e2012015-04-04 12:43:01 +03001266 return self.tk.getboolean(self.tk.call(self._w, "exists", item))
Guilherme Polo5f238482009-01-28 14:41:10 +00001267
1268
1269 def focus(self, item=None):
1270 """If item is specified, sets the focus item to item. Otherwise,
1271 returns the current focus item, or '' if there is none."""
1272 return self.tk.call(self._w, "focus", item)
1273
1274
1275 def heading(self, column, option=None, **kw):
1276 """Query or modify the heading options for the specified column.
1277
1278 If kw is not given, returns a dict of the heading option values. If
1279 option is specified then the value for that option is returned.
1280 Otherwise, sets the options to the corresponding values.
1281
1282 Valid options/values are:
1283 text: text
1284 The text to display in the column heading
1285 image: image_name
1286 Specifies an image to display to the right of the column
1287 heading
1288 anchor: anchor
1289 Specifies how the heading text should be aligned. One of
1290 the standard Tk anchor values
1291 command: callback
1292 A callback to be invoked when the heading label is
1293 pressed.
1294
1295 To configure the tree column heading, call this with column = "#0" """
1296 cmd = kw.get('command')
1297 if cmd and not isinstance(cmd, str):
1298 # callback not registered yet, do it now
1299 kw['command'] = self.master.register(cmd, self._substitute)
1300
1301 if option is not None:
1302 kw[option] = None
1303
Serhiy Storchakab49eff22014-05-28 18:38:27 +03001304 return _val_or_dict(self.tk, kw, self._w, 'heading', column)
Guilherme Polo5f238482009-01-28 14:41:10 +00001305
1306
1307 def identify(self, component, x, y):
1308 """Returns a description of the specified component under the
1309 point given by x and y, or the empty string if no such component
1310 is present at that position."""
1311 return self.tk.call(self._w, "identify", component, x, y)
1312
1313
1314 def identify_row(self, y):
1315 """Returns the item ID of the item at position y."""
1316 return self.identify("row", 0, y)
1317
1318
1319 def identify_column(self, x):
1320 """Returns the data column identifier of the cell at position x.
1321
1322 The tree column has ID #0."""
1323 return self.identify("column", x, 0)
1324
1325
1326 def identify_region(self, x, y):
1327 """Returns one of:
1328
1329 heading: Tree heading area.
1330 separator: Space between two columns headings;
1331 tree: The tree area.
1332 cell: A data cell.
1333
1334 * Availability: Tk 8.6"""
1335 return self.identify("region", x, y)
1336
1337
1338 def identify_element(self, x, y):
1339 """Returns the element at position x, y.
1340
1341 * Availability: Tk 8.6"""
1342 return self.identify("element", x, y)
1343
1344
1345 def index(self, item):
1346 """Returns the integer index of item within its parent's list
1347 of children."""
Serhiy Storchakaa21acb52014-01-07 19:27:42 +02001348 return self.tk.getint(self.tk.call(self._w, "index", item))
Guilherme Polo5f238482009-01-28 14:41:10 +00001349
1350
1351 def insert(self, parent, index, iid=None, **kw):
1352 """Creates a new item and return the item identifier of the newly
1353 created item.
1354
1355 parent is the item ID of the parent item, or the empty string
1356 to create a new top-level item. index is an integer, or the value
1357 end, specifying where in the list of parent's children to insert
1358 the new item. If index is less than or equal to zero, the new node
1359 is inserted at the beginning, if index is greater than or equal to
1360 the current number of children, it is inserted at the end. If iid
1361 is specified, it is used as the item identifier, iid must not
1362 already exist in the tree. Otherwise, a new unique identifier
1363 is generated."""
1364 opts = _format_optdict(kw)
Garvit Khatri3ab44c02018-03-26 12:32:05 +05301365 if iid is not None:
Guilherme Polo5f238482009-01-28 14:41:10 +00001366 res = self.tk.call(self._w, "insert", parent, index,
1367 "-id", iid, *opts)
1368 else:
1369 res = self.tk.call(self._w, "insert", parent, index, *opts)
1370
1371 return res
1372
1373
1374 def item(self, item, option=None, **kw):
1375 """Query or modify the options for the specified item.
1376
1377 If no options are given, a dict with options/values for the item
1378 is returned. If option is specified then the value for that option
1379 is returned. Otherwise, sets the options to the corresponding
1380 values as given by kw."""
1381 if option is not None:
1382 kw[option] = None
Serhiy Storchakab49eff22014-05-28 18:38:27 +03001383 return _val_or_dict(self.tk, kw, self._w, "item", item)
Guilherme Polo5f238482009-01-28 14:41:10 +00001384
1385
1386 def move(self, item, parent, index):
1387 """Moves item to position index in parent's list of children.
1388
1389 It is illegal to move an item under one of its descendants. If
1390 index is less than or equal to zero, item is moved to the
1391 beginning, if greater than or equal to the number of children,
1392 it is moved to the end. If item was detached it is reattached."""
1393 self.tk.call(self._w, "move", item, parent, index)
1394
1395 reattach = move # A sensible method name for reattaching detached items
1396
1397
1398 def next(self, item):
1399 """Returns the identifier of item's next sibling, or '' if item
1400 is the last child of its parent."""
1401 return self.tk.call(self._w, "next", item)
1402
1403
1404 def parent(self, item):
1405 """Returns the ID of the parent of item, or '' if item is at the
1406 top level of the hierarchy."""
1407 return self.tk.call(self._w, "parent", item)
1408
1409
1410 def prev(self, item):
1411 """Returns the identifier of item's previous sibling, or '' if
1412 item is the first child of its parent."""
1413 return self.tk.call(self._w, "prev", item)
1414
1415
1416 def see(self, item):
1417 """Ensure that item is visible.
1418
1419 Sets all of item's ancestors open option to True, and scrolls
1420 the widget if necessary so that item is within the visible
1421 portion of the tree."""
1422 self.tk.call(self._w, "see", item)
1423
1424
Serhiy Storchaka97f1ca12018-02-01 18:49:21 +02001425 def selection(self):
Serhiy Storchakab84f0292016-06-20 00:05:40 +03001426 """Returns the tuple of selected items."""
Serhiy Storchaka97f1ca12018-02-01 18:49:21 +02001427 return self.tk.splitlist(self.tk.call(self._w, "selection"))
Guilherme Polo5f238482009-01-28 14:41:10 +00001428
1429
Serhiy Storchakab84f0292016-06-20 00:05:40 +03001430 def _selection(self, selop, items):
1431 if len(items) == 1 and isinstance(items[0], (tuple, list)):
1432 items = items[0]
1433
1434 self.tk.call(self._w, "selection", selop, items)
Guilherme Polo5f238482009-01-28 14:41:10 +00001435
1436
Serhiy Storchakab84f0292016-06-20 00:05:40 +03001437 def selection_set(self, *items):
1438 """The specified items becomes the new selection."""
1439 self._selection("set", items)
Guilherme Polo5f238482009-01-28 14:41:10 +00001440
1441
Serhiy Storchakab84f0292016-06-20 00:05:40 +03001442 def selection_add(self, *items):
1443 """Add all of the specified items to the selection."""
1444 self._selection("add", items)
Guilherme Polo5f238482009-01-28 14:41:10 +00001445
1446
Serhiy Storchakab84f0292016-06-20 00:05:40 +03001447 def selection_remove(self, *items):
1448 """Remove all of the specified items from the selection."""
1449 self._selection("remove", items)
1450
1451
1452 def selection_toggle(self, *items):
1453 """Toggle the selection state of each specified item."""
1454 self._selection("toggle", items)
Guilherme Polo5f238482009-01-28 14:41:10 +00001455
1456
1457 def set(self, item, column=None, value=None):
Serhiy Storchaka8f0a1d02014-09-06 22:47:58 +03001458 """Query or set the value of given item.
1459
1460 With one argument, return a dictionary of column/value pairs
1461 for the specified item. With two arguments, return the current
1462 value of the specified column. With three arguments, set the
Guilherme Polo5f238482009-01-28 14:41:10 +00001463 value of given column in given item to the specified value."""
1464 res = self.tk.call(self._w, "set", item, column, value)
1465 if column is None and value is None:
Serhiy Storchaka8f0a1d02014-09-06 22:47:58 +03001466 return _splitdict(self.tk, res,
1467 cut_minus=False, conv=_tclobj_to_py)
Guilherme Polo5f238482009-01-28 14:41:10 +00001468 else:
1469 return res
1470
1471
1472 def tag_bind(self, tagname, sequence=None, callback=None):
1473 """Bind a callback for the given event sequence to the tag tagname.
1474 When an event is delivered to an item, the callbacks for each
1475 of the item's tags option are called."""
1476 self._bind((self._w, "tag", "bind", tagname), sequence, callback, add=0)
1477
1478
1479 def tag_configure(self, tagname, option=None, **kw):
1480 """Query or modify the options for the specified tagname.
1481
1482 If kw is not given, returns a dict of the option settings for tagname.
1483 If option is specified, returns the value for that option for the
1484 specified tagname. Otherwise, sets the options to the corresponding
1485 values for the given tagname."""
1486 if option is not None:
1487 kw[option] = None
Serhiy Storchakab49eff22014-05-28 18:38:27 +03001488 return _val_or_dict(self.tk, kw, self._w, "tag", "configure",
Guilherme Polo5f238482009-01-28 14:41:10 +00001489 tagname)
1490
1491
1492 def tag_has(self, tagname, item=None):
1493 """If item is specified, returns 1 or 0 depending on whether the
1494 specified item has the given tagname. Otherwise, returns a list of
1495 all items which have the specified tag.
1496
1497 * Availability: Tk 8.6"""
Serhiy Storchaka8e92f572014-11-07 12:02:31 +02001498 if item is None:
1499 return self.tk.splitlist(
1500 self.tk.call(self._w, "tag", "has", tagname))
1501 else:
1502 return self.tk.getboolean(
Serhiy Storchakaa21acb52014-01-07 19:27:42 +02001503 self.tk.call(self._w, "tag", "has", tagname, item))
Guilherme Polo5f238482009-01-28 14:41:10 +00001504
1505
Guilherme Polo5f238482009-01-28 14:41:10 +00001506# Extensions
1507
1508class LabeledScale(Frame):
1509 """A Ttk Scale widget with a Ttk Label widget indicating its
1510 current value.
1511
1512 The Ttk Scale can be accessed through instance.scale, and Ttk Label
1513 can be accessed through instance.label"""
1514
1515 def __init__(self, master=None, variable=None, from_=0, to=10, **kw):
Serhiy Storchaka6a7b3a72016-04-17 08:32:47 +03001516 """Construct a horizontal LabeledScale with parent master, a
Guilherme Polo5f238482009-01-28 14:41:10 +00001517 variable to be associated with the Ttk Scale widget and its range.
1518 If variable is not specified, a tkinter.IntVar is created.
1519
1520 WIDGET-SPECIFIC OPTIONS
1521
1522 compound: 'top' or 'bottom'
1523 Specifies how to display the label relative to the scale.
1524 Defaults to 'top'.
1525 """
1526 self._label_top = kw.pop('compound', 'top') == 'top'
1527
1528 Frame.__init__(self, master, **kw)
1529 self._variable = variable or tkinter.IntVar(master)
1530 self._variable.set(from_)
1531 self._last_valid = from_
1532
1533 self.label = Label(self)
1534 self.scale = Scale(self, variable=self._variable, from_=from_, to=to)
1535 self.scale.bind('<<RangeChanged>>', self._adjust)
1536
1537 # position scale and label according to the compound option
1538 scale_side = 'bottom' if self._label_top else 'top'
1539 label_side = 'top' if scale_side == 'bottom' else 'bottom'
1540 self.scale.pack(side=scale_side, fill='x')
1541 tmp = Label(self).pack(side=label_side) # place holder
1542 self.label.place(anchor='n' if label_side == 'top' else 's')
1543
1544 # update the label as scale or variable changes
1545 self.__tracecb = self._variable.trace_variable('w', self._adjust)
1546 self.bind('<Configure>', self._adjust)
1547 self.bind('<Map>', self._adjust)
1548
1549
1550 def destroy(self):
1551 """Destroy this widget and possibly its associated variable."""
1552 try:
1553 self._variable.trace_vdelete('w', self.__tracecb)
1554 except AttributeError:
Guilherme Polo5f238482009-01-28 14:41:10 +00001555 pass
1556 else:
1557 del self._variable
Victor Stinnercd7e9c12017-08-08 19:41:21 +02001558 super().destroy()
1559 self.label = None
1560 self.scale = None
Guilherme Polo5f238482009-01-28 14:41:10 +00001561
1562
1563 def _adjust(self, *args):
1564 """Adjust the label position according to the scale."""
1565 def adjust_label():
1566 self.update_idletasks() # "force" scale redraw
1567
1568 x, y = self.scale.coords()
1569 if self._label_top:
1570 y = self.scale.winfo_y() - self.label.winfo_reqheight()
1571 else:
1572 y = self.scale.winfo_reqheight() + self.label.winfo_reqheight()
1573
1574 self.label.place_configure(x=x, y=y)
1575
Serhiy Storchakaa21acb52014-01-07 19:27:42 +02001576 from_ = _to_number(self.scale['from'])
1577 to = _to_number(self.scale['to'])
Guilherme Polo5f238482009-01-28 14:41:10 +00001578 if to < from_:
1579 from_, to = to, from_
1580 newval = self._variable.get()
1581 if not from_ <= newval <= to:
1582 # value outside range, set value back to the last valid one
1583 self.value = self._last_valid
1584 return
1585
1586 self._last_valid = newval
1587 self.label['text'] = newval
1588 self.after_idle(adjust_label)
1589
Serhiy Storchakabdf6b912017-03-19 08:40:32 +02001590 @property
1591 def value(self):
Guilherme Polo5f238482009-01-28 14:41:10 +00001592 """Return current scale value."""
1593 return self._variable.get()
1594
Serhiy Storchakabdf6b912017-03-19 08:40:32 +02001595 @value.setter
1596 def value(self, val):
Guilherme Polo5f238482009-01-28 14:41:10 +00001597 """Set new scale value."""
1598 self._variable.set(val)
1599
1600
Guilherme Polo5f238482009-01-28 14:41:10 +00001601class OptionMenu(Menubutton):
1602 """Themed OptionMenu, based after tkinter's OptionMenu, which allows
1603 the user to select a value from a menu."""
1604
1605 def __init__(self, master, variable, default=None, *values, **kwargs):
1606 """Construct a themed OptionMenu widget with master as the parent,
1607 the resource textvariable set to variable, the initially selected
1608 value specified by the default parameter, the menu values given by
1609 *values and additional keywords.
1610
1611 WIDGET-SPECIFIC OPTIONS
1612
1613 style: stylename
1614 Menubutton style.
1615 direction: 'above', 'below', 'left', 'right', or 'flush'
1616 Menubutton direction.
1617 command: callback
1618 A callback that will be invoked after selecting an item.
1619 """
1620 kw = {'textvariable': variable, 'style': kwargs.pop('style', None),
1621 'direction': kwargs.pop('direction', None)}
1622 Menubutton.__init__(self, master, **kw)
1623 self['menu'] = tkinter.Menu(self, tearoff=False)
1624
1625 self._variable = variable
1626 self._callback = kwargs.pop('command', None)
1627 if kwargs:
1628 raise tkinter.TclError('unknown option -%s' % (
1629 next(iter(kwargs.keys()))))
1630
1631 self.set_menu(default, *values)
1632
1633
1634 def __getitem__(self, item):
1635 if item == 'menu':
1636 return self.nametowidget(Menubutton.__getitem__(self, item))
1637
1638 return Menubutton.__getitem__(self, item)
1639
1640
1641 def set_menu(self, default=None, *values):
1642 """Build a new menu of radiobuttons with *values and optionally
1643 a default value."""
1644 menu = self['menu']
1645 menu.delete(0, 'end')
1646 for val in values:
1647 menu.add_radiobutton(label=val,
csabellaa568e522017-07-31 05:30:09 -04001648 command=tkinter._setit(self._variable, val, self._callback),
1649 variable=self._variable)
Guilherme Polo5f238482009-01-28 14:41:10 +00001650
1651 if default:
1652 self._variable.set(default)
1653
1654
1655 def destroy(self):
1656 """Destroy this widget and its associated variable."""
Victor Stinnercd7e9c12017-08-08 19:41:21 +02001657 try:
1658 del self._variable
1659 except AttributeError:
1660 pass
1661 super().destroy()