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