Debian Codegraph @

Lib/tkinter/ttk.py

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