PageRenderTime 55ms CodeModel.GetById 15ms RepoModel.GetById 0ms app.codeStats 1ms

/External.LCA_RESTRICTED/Languages/CPython/27/Lib/lib-tk/ttk.py

http://github.com/IronLanguages/main
Python | 1635 lines | 1592 code | 14 blank | 29 comment | 5 complexity | f5ec4c64cd24f658274e3f85f519130b MD5 | raw file
Possible License(s): CPL-1.0, BSD-3-Clause, ISC, GPL-2.0, MPL-2.0-no-copyleft-exception

Large files files are truncated, but you can click here to view the full file

  1. """Ttk wrapper.
  2. This module provides classes to allow using Tk themed widget set.
  3. Ttk is based on a revised and enhanced version of
  4. TIP #48 (http://tip.tcl.tk/48) specified style engine.
  5. Its basic idea is to separate, to the extent possible, the code
  6. implementing a widget's behavior from the code implementing its
  7. appearance. Widget class bindings are primarily responsible for
  8. maintaining the widget state and invoking callbacks, all aspects
  9. of the widgets appearance lies at Themes.
  10. """
  11. __version__ = "0.3.1"
  12. __author__ = "Guilherme Polo <ggpolo@gmail.com>"
  13. __all__ = ["Button", "Checkbutton", "Combobox", "Entry", "Frame", "Label",
  14. "Labelframe", "LabelFrame", "Menubutton", "Notebook", "Panedwindow",
  15. "PanedWindow", "Progressbar", "Radiobutton", "Scale", "Scrollbar",
  16. "Separator", "Sizegrip", "Style", "Treeview",
  17. # Extensions
  18. "LabeledScale", "OptionMenu",
  19. # functions
  20. "tclobjs_to_py", "setup_master"]
  21. import Tkinter
  22. _flatten = Tkinter._flatten
  23. # Verify if Tk is new enough to not need the Tile package
  24. _REQUIRE_TILE = True if Tkinter.TkVersion < 8.5 else False
  25. def _load_tile(master):
  26. if _REQUIRE_TILE:
  27. import os
  28. tilelib = os.environ.get('TILE_LIBRARY')
  29. if tilelib:
  30. # append custom tile path to the list of directories that
  31. # Tcl uses when attempting to resolve packages with the package
  32. # command
  33. master.tk.eval(
  34. 'global auto_path; '
  35. 'lappend auto_path {%s}' % tilelib)
  36. master.tk.eval('package require tile') # TclError may be raised here
  37. master._tile_loaded = True
  38. def _format_optdict(optdict, script=False, ignore=None):
  39. """Formats optdict to a tuple to pass it to tk.call.
  40. E.g. (script=False):
  41. {'foreground': 'blue', 'padding': [1, 2, 3, 4]} returns:
  42. ('-foreground', 'blue', '-padding', '1 2 3 4')"""
  43. format = "%s" if not script else "{%s}"
  44. opts = []
  45. for opt, value in optdict.iteritems():
  46. if ignore and opt in ignore:
  47. continue
  48. if isinstance(value, (list, tuple)):
  49. v = []
  50. for val in value:
  51. if isinstance(val, basestring):
  52. v.append(unicode(val) if val else '{}')
  53. else:
  54. v.append(str(val))
  55. # format v according to the script option, but also check for
  56. # space in any value in v in order to group them correctly
  57. value = format % ' '.join(
  58. ('{%s}' if ' ' in val else '%s') % val for val in v)
  59. if script and value == '':
  60. value = '{}' # empty string in Python is equivalent to {} in Tcl
  61. opts.append(("-%s" % opt, value))
  62. # Remember: _flatten skips over None
  63. return _flatten(opts)
  64. def _format_mapdict(mapdict, script=False):
  65. """Formats mapdict to pass it to tk.call.
  66. E.g. (script=False):
  67. {'expand': [('active', 'selected', 'grey'), ('focus', [1, 2, 3, 4])]}
  68. returns:
  69. ('-expand', '{active selected} grey focus {1, 2, 3, 4}')"""
  70. # if caller passes a Tcl script to tk.call, all the values need to
  71. # be grouped into words (arguments to a command in Tcl dialect)
  72. format = "%s" if not script else "{%s}"
  73. opts = []
  74. for opt, value in mapdict.iteritems():
  75. opt_val = []
  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. for statespec in value:
  79. state, val = statespec[:-1], statespec[-1]
  80. if len(state) > 1: # group multiple states
  81. state = "{%s}" % ' '.join(state)
  82. else: # single state
  83. # if it is empty (something that evaluates to False), then
  84. # format it to Tcl code to denote the "normal" state
  85. state = state[0] or '{}'
  86. if isinstance(val, (list, tuple)): # val needs to be grouped
  87. val = "{%s}" % ' '.join(map(str, val))
  88. opt_val.append("%s %s" % (state, val))
  89. opts.append(("-%s" % opt, format % ' '.join(opt_val)))
  90. return _flatten(opts)
  91. def _format_elemcreate(etype, script=False, *args, **kw):
  92. """Formats args and kw according to the given element factory etype."""
  93. spec = None
  94. opts = ()
  95. if etype in ("image", "vsapi"):
  96. if etype == "image": # define an element based on an image
  97. # first arg should be the default image name
  98. iname = args[0]
  99. # next args, if any, are statespec/value pairs which is almost
  100. # a mapdict, but we just need the value
  101. imagespec = _format_mapdict({None: args[1:]})[1]
  102. spec = "%s %s" % (iname, imagespec)
  103. else:
  104. # define an element whose visual appearance is drawn using the
  105. # Microsoft Visual Styles API which is responsible for the
  106. # themed styles on Windows XP and Vista.
  107. # Availability: Tk 8.6, Windows XP and Vista.
  108. class_name, part_id = args[:2]
  109. statemap = _format_mapdict({None: args[2:]})[1]
  110. spec = "%s %s %s" % (class_name, part_id, statemap)
  111. opts = _format_optdict(kw, script)
  112. elif etype == "from": # clone an element
  113. # it expects a themename and optionally an element to clone from,
  114. # otherwise it will clone {} (empty element)
  115. spec = args[0] # theme name
  116. if len(args) > 1: # elementfrom specified
  117. opts = (args[1], )
  118. if script:
  119. spec = '{%s}' % spec
  120. opts = ' '.join(map(str, opts))
  121. return spec, opts
  122. def _format_layoutlist(layout, indent=0, indent_size=2):
  123. """Formats a layout list so we can pass the result to ttk::style
  124. layout and ttk::style settings. Note that the layout doesn't has to
  125. be a list necessarily.
  126. E.g.:
  127. [("Menubutton.background", None),
  128. ("Menubutton.button", {"children":
  129. [("Menubutton.focus", {"children":
  130. [("Menubutton.padding", {"children":
  131. [("Menubutton.label", {"side": "left", "expand": 1})]
  132. })]
  133. })]
  134. }),
  135. ("Menubutton.indicator", {"side": "right"})
  136. ]
  137. returns:
  138. Menubutton.background
  139. Menubutton.button -children {
  140. Menubutton.focus -children {
  141. Menubutton.padding -children {
  142. Menubutton.label -side left -expand 1
  143. }
  144. }
  145. }
  146. Menubutton.indicator -side right"""
  147. script = []
  148. for layout_elem in layout:
  149. elem, opts = layout_elem
  150. opts = opts or {}
  151. fopts = ' '.join(map(str, _format_optdict(opts, True, "children")))
  152. head = "%s%s%s" % (' ' * indent, elem, (" %s" % fopts) if fopts else '')
  153. if "children" in opts:
  154. script.append(head + " -children {")
  155. indent += indent_size
  156. newscript, indent = _format_layoutlist(opts['children'], indent,
  157. indent_size)
  158. script.append(newscript)
  159. indent -= indent_size
  160. script.append('%s}' % (' ' * indent))
  161. else:
  162. script.append(head)
  163. return '\n'.join(script), indent
  164. def _script_from_settings(settings):
  165. """Returns an appropriate script, based on settings, according to
  166. theme_settings definition to be used by theme_settings and
  167. theme_create."""
  168. script = []
  169. # a script will be generated according to settings passed, which
  170. # will then be evaluated by Tcl
  171. for name, opts in settings.iteritems():
  172. # will format specific keys according to Tcl code
  173. if opts.get('configure'): # format 'configure'
  174. s = ' '.join(map(unicode, _format_optdict(opts['configure'], True)))
  175. script.append("ttk::style configure %s %s;" % (name, s))
  176. if opts.get('map'): # format 'map'
  177. s = ' '.join(map(unicode, _format_mapdict(opts['map'], True)))
  178. script.append("ttk::style map %s %s;" % (name, s))
  179. if 'layout' in opts: # format 'layout' which may be empty
  180. if not opts['layout']:
  181. s = 'null' # could be any other word, but this one makes sense
  182. else:
  183. s, _ = _format_layoutlist(opts['layout'])
  184. script.append("ttk::style layout %s {\n%s\n}" % (name, s))
  185. if opts.get('element create'): # format 'element create'
  186. eopts = opts['element create']
  187. etype = eopts[0]
  188. # find where args end, and where kwargs start
  189. argc = 1 # etype was the first one
  190. while argc < len(eopts) and not hasattr(eopts[argc], 'iteritems'):
  191. argc += 1
  192. elemargs = eopts[1:argc]
  193. elemkw = eopts[argc] if argc < len(eopts) and eopts[argc] else {}
  194. spec, opts = _format_elemcreate(etype, True, *elemargs, **elemkw)
  195. script.append("ttk::style element create %s %s %s %s" % (
  196. name, etype, spec, opts))
  197. return '\n'.join(script)
  198. def _dict_from_tcltuple(ttuple, cut_minus=True):
  199. """Break tuple in pairs, format it properly, then build the return
  200. dict. If cut_minus is True, the supposed '-' prefixing options will
  201. be removed.
  202. ttuple is expected to contain an even number of elements."""
  203. opt_start = 1 if cut_minus else 0
  204. retdict = {}
  205. it = iter(ttuple)
  206. for opt, val in zip(it, it):
  207. retdict[str(opt)[opt_start:]] = val
  208. return tclobjs_to_py(retdict)
  209. def _list_from_statespec(stuple):
  210. """Construct a list from the given statespec tuple according to the
  211. accepted statespec accepted by _format_mapdict."""
  212. nval = []
  213. for val in stuple:
  214. typename = getattr(val, 'typename', None)
  215. if typename is None:
  216. nval.append(val)
  217. else: # this is a Tcl object
  218. val = str(val)
  219. if typename == 'StateSpec':
  220. val = val.split()
  221. nval.append(val)
  222. it = iter(nval)
  223. return [_flatten(spec) for spec in zip(it, it)]
  224. def _list_from_layouttuple(ltuple):
  225. """Construct a list from the tuple returned by ttk::layout, this is
  226. somewhat the reverse of _format_layoutlist."""
  227. res = []
  228. indx = 0
  229. while indx < len(ltuple):
  230. name = ltuple[indx]
  231. opts = {}
  232. res.append((name, opts))
  233. indx += 1
  234. while indx < len(ltuple): # grab name's options
  235. opt, val = ltuple[indx:indx + 2]
  236. if not opt.startswith('-'): # found next name
  237. break
  238. opt = opt[1:] # remove the '-' from the option
  239. indx += 2
  240. if opt == 'children':
  241. val = _list_from_layouttuple(val)
  242. opts[opt] = val
  243. return res
  244. def _val_or_dict(options, func, *args):
  245. """Format options then call func with args and options and return
  246. the appropriate result.
  247. If no option is specified, a dict is returned. If a option is
  248. specified with the None value, the value for that option is returned.
  249. Otherwise, the function just sets the passed options and the caller
  250. shouldn't be expecting a return value anyway."""
  251. options = _format_optdict(options)
  252. res = func(*(args + options))
  253. if len(options) % 2: # option specified without a value, return its value
  254. return res
  255. return _dict_from_tcltuple(res)
  256. def _convert_stringval(value):
  257. """Converts a value to, hopefully, a more appropriate Python object."""
  258. value = unicode(value)
  259. try:
  260. value = int(value)
  261. except (ValueError, TypeError):
  262. pass
  263. return value
  264. def tclobjs_to_py(adict):
  265. """Returns adict with its values converted from Tcl objects to Python
  266. objects."""
  267. for opt, val in adict.iteritems():
  268. if val and hasattr(val, '__len__') and not isinstance(val, basestring):
  269. if getattr(val[0], 'typename', None) == 'StateSpec':
  270. val = _list_from_statespec(val)
  271. else:
  272. val = map(_convert_stringval, val)
  273. elif hasattr(val, 'typename'): # some other (single) Tcl object
  274. val = _convert_stringval(val)
  275. adict[opt] = val
  276. return adict
  277. def setup_master(master=None):
  278. """If master is not None, itself is returned. If master is None,
  279. the default master is returned if there is one, otherwise a new
  280. master is created and returned.
  281. If it is not allowed to use the default root and master is None,
  282. RuntimeError is raised."""
  283. if master is None:
  284. if Tkinter._support_default_root:
  285. master = Tkinter._default_root or Tkinter.Tk()
  286. else:
  287. raise RuntimeError(
  288. "No master specified and Tkinter is "
  289. "configured to not support default root")
  290. return master
  291. class Style(object):
  292. """Manipulate style database."""
  293. _name = "ttk::style"
  294. def __init__(self, master=None):
  295. master = setup_master(master)
  296. if not getattr(master, '_tile_loaded', False):
  297. # Load tile now, if needed
  298. _load_tile(master)
  299. self.master = master
  300. self.tk = self.master.tk
  301. def configure(self, style, query_opt=None, **kw):
  302. """Query or sets the default value of the specified option(s) in
  303. style.
  304. Each key in kw is an option and each value is either a string or
  305. a sequence identifying the value for that option."""
  306. if query_opt is not None:
  307. kw[query_opt] = None
  308. return _val_or_dict(kw, self.tk.call, self._name, "configure", style)
  309. def map(self, style, query_opt=None, **kw):
  310. """Query or sets dynamic values of the specified option(s) in
  311. style.
  312. Each key in kw is an option and each value should be a list or a
  313. tuple (usually) containing statespecs grouped in tuples, or list,
  314. or something else of your preference. A statespec is compound of
  315. one or more states and then a value."""
  316. if query_opt is not None:
  317. return _list_from_statespec(
  318. self.tk.call(self._name, "map", style, '-%s' % query_opt))
  319. return _dict_from_tcltuple(
  320. self.tk.call(self._name, "map", style, *(_format_mapdict(kw))))
  321. def lookup(self, style, option, state=None, default=None):
  322. """Returns the value specified for option in style.
  323. If state is specified it is expected to be a sequence of one
  324. or more states. If the default argument is set, it is used as
  325. a fallback value in case no specification for option is found."""
  326. state = ' '.join(state) if state else ''
  327. return self.tk.call(self._name, "lookup", style, '-%s' % option,
  328. state, default)
  329. def layout(self, style, layoutspec=None):
  330. """Define the widget layout for given style. If layoutspec is
  331. omitted, return the layout specification for given style.
  332. layoutspec is expected to be a list or an object different than
  333. None that evaluates to False if you want to "turn off" that style.
  334. If it is a list (or tuple, or something else), each item should be
  335. a tuple where the first item is the layout name and the second item
  336. should have the format described below:
  337. LAYOUTS
  338. A layout can contain the value None, if takes no options, or
  339. a dict of options specifying how to arrange the element.
  340. The layout mechanism uses a simplified version of the pack
  341. geometry manager: given an initial cavity, each element is
  342. allocated a parcel. Valid options/values are:
  343. side: whichside
  344. Specifies which side of the cavity to place the
  345. element; one of top, right, bottom or left. If
  346. omitted, the element occupies the entire cavity.
  347. sticky: nswe
  348. Specifies where the element is placed inside its
  349. allocated parcel.
  350. children: [sublayout... ]
  351. Specifies a list of elements to place inside the
  352. element. Each element is a tuple (or other sequence)
  353. where the first item is the layout name, and the other
  354. is a LAYOUT."""
  355. lspec = None
  356. if layoutspec:
  357. lspec = _format_layoutlist(layoutspec)[0]
  358. elif layoutspec is not None: # will disable the layout ({}, '', etc)
  359. lspec = "null" # could be any other word, but this may make sense
  360. # when calling layout(style) later
  361. return _list_from_layouttuple(
  362. self.tk.call(self._name, "layout", style, lspec))
  363. def element_create(self, elementname, etype, *args, **kw):
  364. """Create a new element in the current theme of given etype."""
  365. spec, opts = _format_elemcreate(etype, False, *args, **kw)
  366. self.tk.call(self._name, "element", "create", elementname, etype,
  367. spec, *opts)
  368. def element_names(self):
  369. """Returns the list of elements defined in the current theme."""
  370. return self.tk.call(self._name, "element", "names")
  371. def element_options(self, elementname):
  372. """Return the list of elementname's options."""
  373. return self.tk.call(self._name, "element", "options", elementname)
  374. def theme_create(self, themename, parent=None, settings=None):
  375. """Creates a new theme.
  376. It is an error if themename already exists. If parent is
  377. specified, the new theme will inherit styles, elements and
  378. layouts from the specified parent theme. If settings are present,
  379. they are expected to have the same syntax used for theme_settings."""
  380. script = _script_from_settings(settings) if settings else ''
  381. if parent:
  382. self.tk.call(self._name, "theme", "create", themename,
  383. "-parent", parent, "-settings", script)
  384. else:
  385. self.tk.call(self._name, "theme", "create", themename,
  386. "-settings", script)
  387. def theme_settings(self, themename, settings):
  388. """Temporarily sets the current theme to themename, apply specified
  389. settings and then restore the previous theme.
  390. Each key in settings is a style and each value may contain the
  391. keys 'configure', 'map', 'layout' and 'element create' and they
  392. are expected to have the same format as specified by the methods
  393. configure, map, layout and element_create respectively."""
  394. script = _script_from_settings(settings)
  395. self.tk.call(self._name, "theme", "settings", themename, script)
  396. def theme_names(self):
  397. """Returns a list of all known themes."""
  398. return self.tk.call(self._name, "theme", "names")
  399. def theme_use(self, themename=None):
  400. """If themename is None, returns the theme in use, otherwise, set
  401. the current theme to themename, refreshes all widgets and emits
  402. a <<ThemeChanged>> event."""
  403. if themename is None:
  404. # Starting on Tk 8.6, checking this global is no longer needed
  405. # since it allows doing self.tk.call(self._name, "theme", "use")
  406. return self.tk.eval("return $ttk::currentTheme")
  407. # using "ttk::setTheme" instead of "ttk::style theme use" causes
  408. # the variable currentTheme to be updated, also, ttk::setTheme calls
  409. # "ttk::style theme use" in order to change theme.
  410. self.tk.call("ttk::setTheme", themename)
  411. class Widget(Tkinter.Widget):
  412. """Base class for Tk themed widgets."""
  413. def __init__(self, master, widgetname, kw=None):
  414. """Constructs a Ttk Widget with the parent master.
  415. STANDARD OPTIONS
  416. class, cursor, takefocus, style
  417. SCROLLABLE WIDGET OPTIONS
  418. xscrollcommand, yscrollcommand
  419. LABEL WIDGET OPTIONS
  420. text, textvariable, underline, image, compound, width
  421. WIDGET STATES
  422. active, disabled, focus, pressed, selected, background,
  423. readonly, alternate, invalid
  424. """
  425. master = setup_master(master)
  426. if not getattr(master, '_tile_loaded', False):
  427. # Load tile now, if needed
  428. _load_tile(master)
  429. Tkinter.Widget.__init__(self, master, widgetname, kw=kw)
  430. def identify(self, x, y):
  431. """Returns the name of the element at position x, y, or the empty
  432. string if the point does not lie within any element.
  433. x and y are pixel coordinates relative to the widget."""
  434. return self.tk.call(self._w, "identify", x, y)
  435. def instate(self, statespec, callback=None, *args, **kw):
  436. """Test the widget's state.
  437. If callback is not specified, returns True if the widget state
  438. matches statespec and False otherwise. If callback is specified,
  439. then it will be invoked with *args, **kw if the widget state
  440. matches statespec. statespec is expected to be a sequence."""
  441. ret = self.tk.call(self._w, "instate", ' '.join(statespec))
  442. if ret and callback:
  443. return callback(*args, **kw)
  444. return bool(ret)
  445. def state(self, statespec=None):
  446. """Modify or inquire widget state.
  447. Widget state is returned if statespec is None, otherwise it is
  448. set according to the statespec flags and then a new state spec
  449. is returned indicating which flags were changed. statespec is
  450. expected to be a sequence."""
  451. if statespec is not None:
  452. statespec = ' '.join(statespec)
  453. return self.tk.splitlist(str(self.tk.call(self._w, "state", statespec)))
  454. class Button(Widget):
  455. """Ttk Button widget, displays a textual label and/or image, and
  456. evaluates a command when pressed."""
  457. def __init__(self, master=None, **kw):
  458. """Construct a Ttk Button widget with the parent master.
  459. STANDARD OPTIONS
  460. class, compound, cursor, image, state, style, takefocus,
  461. text, textvariable, underline, width
  462. WIDGET-SPECIFIC OPTIONS
  463. command, default, width
  464. """
  465. Widget.__init__(self, master, "ttk::button", kw)
  466. def invoke(self):
  467. """Invokes the command associated with the button."""
  468. return self.tk.call(self._w, "invoke")
  469. class Checkbutton(Widget):
  470. """Ttk Checkbutton widget which is either in on- or off-state."""
  471. def __init__(self, master=None, **kw):
  472. """Construct a Ttk Checkbutton widget with the parent master.
  473. STANDARD OPTIONS
  474. class, compound, cursor, image, state, style, takefocus,
  475. text, textvariable, underline, width
  476. WIDGET-SPECIFIC OPTIONS
  477. command, offvalue, onvalue, variable
  478. """
  479. Widget.__init__(self, master, "ttk::checkbutton", kw)
  480. def invoke(self):
  481. """Toggles between the selected and deselected states and
  482. invokes the associated command. If the widget is currently
  483. selected, sets the option variable to the offvalue option
  484. and deselects the widget; otherwise, sets the option variable
  485. to the option onvalue.
  486. Returns the result of the associated command."""
  487. return self.tk.call(self._w, "invoke")
  488. class Entry(Widget, Tkinter.Entry):
  489. """Ttk Entry widget displays a one-line text string and allows that
  490. string to be edited by the user."""
  491. def __init__(self, master=None, widget=None, **kw):
  492. """Constructs a Ttk Entry widget with the parent master.
  493. STANDARD OPTIONS
  494. class, cursor, style, takefocus, xscrollcommand
  495. WIDGET-SPECIFIC OPTIONS
  496. exportselection, invalidcommand, justify, show, state,
  497. textvariable, validate, validatecommand, width
  498. VALIDATION MODES
  499. none, key, focus, focusin, focusout, all
  500. """
  501. Widget.__init__(self, master, widget or "ttk::entry", kw)
  502. def bbox(self, index):
  503. """Return a tuple of (x, y, width, height) which describes the
  504. bounding box of the character given by index."""
  505. return self.tk.call(self._w, "bbox", index)
  506. def identify(self, x, y):
  507. """Returns the name of the element at position x, y, or the
  508. empty string if the coordinates are outside the window."""
  509. return self.tk.call(self._w, "identify", x, y)
  510. def validate(self):
  511. """Force revalidation, independent of the conditions specified
  512. by the validate option. Returns False if validation fails, True
  513. if it succeeds. Sets or clears the invalid state accordingly."""
  514. return bool(self.tk.call(self._w, "validate"))
  515. class Combobox(Entry):
  516. """Ttk Combobox widget combines a text field with a pop-down list of
  517. values."""
  518. def __init__(self, master=None, **kw):
  519. """Construct a Ttk Combobox widget with the parent master.
  520. STANDARD OPTIONS
  521. class, cursor, style, takefocus
  522. WIDGET-SPECIFIC OPTIONS
  523. exportselection, justify, height, postcommand, state,
  524. textvariable, values, width
  525. """
  526. # The "values" option may need special formatting, so leave to
  527. # _format_optdict the responsibility to format it
  528. if "values" in kw:
  529. kw["values"] = _format_optdict({'v': kw["values"]})[1]
  530. Entry.__init__(self, master, "ttk::combobox", **kw)
  531. def __setitem__(self, item, value):
  532. if item == "values":
  533. value = _format_optdict({item: value})[1]
  534. Entry.__setitem__(self, item, value)
  535. def configure(self, cnf=None, **kw):
  536. """Custom Combobox configure, created to properly format the values
  537. option."""
  538. if "values" in kw:
  539. kw["values"] = _format_optdict({'v': kw["values"]})[1]
  540. return Entry.configure(self, cnf, **kw)
  541. def current(self, newindex=None):
  542. """If newindex is supplied, sets the combobox value to the
  543. element at position newindex in the list of values. Otherwise,
  544. returns the index of the current value in the list of values
  545. or -1 if the current value does not appear in the list."""
  546. return self.tk.call(self._w, "current", newindex)
  547. def set(self, value):
  548. """Sets the value of the combobox to value."""
  549. self.tk.call(self._w, "set", value)
  550. class Frame(Widget):
  551. """Ttk Frame widget is a container, used to group other widgets
  552. together."""
  553. def __init__(self, master=None, **kw):
  554. """Construct a Ttk Frame with parent master.
  555. STANDARD OPTIONS
  556. class, cursor, style, takefocus
  557. WIDGET-SPECIFIC OPTIONS
  558. borderwidth, relief, padding, width, height
  559. """
  560. Widget.__init__(self, master, "ttk::frame", kw)
  561. class Label(Widget):
  562. """Ttk Label widget displays a textual label and/or image."""
  563. def __init__(self, master=None, **kw):
  564. """Construct a Ttk Label with parent master.
  565. STANDARD OPTIONS
  566. class, compound, cursor, image, style, takefocus, text,
  567. textvariable, underline, width
  568. WIDGET-SPECIFIC OPTIONS
  569. anchor, background, font, foreground, justify, padding,
  570. relief, text, wraplength
  571. """
  572. Widget.__init__(self, master, "ttk::label", kw)
  573. class Labelframe(Widget):
  574. """Ttk Labelframe widget is a container used to group other widgets
  575. together. It has an optional label, which may be a plain text string
  576. or another widget."""
  577. def __init__(self, master=None, **kw):
  578. """Construct a Ttk Labelframe with parent master.
  579. STANDARD OPTIONS
  580. class, cursor, style, takefocus
  581. WIDGET-SPECIFIC OPTIONS
  582. labelanchor, text, underline, padding, labelwidget, width,
  583. height
  584. """
  585. Widget.__init__(self, master, "ttk::labelframe", kw)
  586. LabelFrame = Labelframe # Tkinter name compatibility
  587. class Menubutton(Widget):
  588. """Ttk Menubutton widget displays a textual label and/or image, and
  589. displays a menu when pressed."""
  590. def __init__(self, master=None, **kw):
  591. """Construct a Ttk Menubutton with parent master.
  592. STANDARD OPTIONS
  593. class, compound, cursor, image, state, style, takefocus,
  594. text, textvariable, underline, width
  595. WIDGET-SPECIFIC OPTIONS
  596. direction, menu
  597. """
  598. Widget.__init__(self, master, "ttk::menubutton", kw)
  599. class Notebook(Widget):
  600. """Ttk Notebook widget manages a collection of windows and displays
  601. a single one at a time. Each child window is associated with a tab,
  602. which the user may select to change the currently-displayed window."""
  603. def __init__(self, master=None, **kw):
  604. """Construct a Ttk Notebook with parent master.
  605. STANDARD OPTIONS
  606. class, cursor, style, takefocus
  607. WIDGET-SPECIFIC OPTIONS
  608. height, padding, width
  609. TAB OPTIONS
  610. state, sticky, padding, text, image, compound, underline
  611. TAB IDENTIFIERS (tab_id)
  612. The tab_id argument found in several methods may take any of
  613. the following forms:
  614. * An integer between zero and the number of tabs
  615. * The name of a child window
  616. * A positional specification of the form "@x,y", which
  617. defines the tab
  618. * The string "current", which identifies the
  619. currently-selected tab
  620. * The string "end", which returns the number of tabs (only
  621. valid for method index)
  622. """
  623. Widget.__init__(self, master, "ttk::notebook", kw)
  624. def add(self, child, **kw):
  625. """Adds a new tab to the notebook.
  626. If window is currently managed by the notebook but hidden, it is
  627. restored to its previous position."""
  628. self.tk.call(self._w, "add", child, *(_format_optdict(kw)))
  629. def forget(self, tab_id):
  630. """Removes the tab specified by tab_id, unmaps and unmanages the
  631. associated window."""
  632. self.tk.call(self._w, "forget", tab_id)
  633. def hide(self, tab_id):
  634. """Hides the tab specified by tab_id.
  635. The tab will not be displayed, but the associated window remains
  636. managed by the notebook and its configuration remembered. Hidden
  637. tabs may be restored with the add command."""
  638. self.tk.call(self._w, "hide", tab_id)
  639. def identify(self, x, y):
  640. """Returns the name of the tab element at position x, y, or the
  641. empty string if none."""
  642. return self.tk.call(self._w, "identify", x, y)
  643. def index(self, tab_id):
  644. """Returns the numeric index of the tab specified by tab_id, or
  645. the total number of tabs if tab_id is the string "end"."""
  646. return self.tk.call(self._w, "index", tab_id)
  647. def insert(self, pos, child, **kw):
  648. """Inserts a pane at the specified position.
  649. pos is either the string end, an integer index, or the name of
  650. a managed child. If child is already managed by the notebook,
  651. moves it to the specified position."""
  652. self.tk.call(self._w, "insert", pos, child, *(_format_optdict(kw)))
  653. def select(self, tab_id=None):
  654. """Selects the specified tab.
  655. The associated child window will be displayed, and the
  656. previously-selected window (if different) is unmapped. If tab_id
  657. is omitted, returns the widget name of the currently selected
  658. pane."""
  659. return self.tk.call(self._w, "select", tab_id)
  660. def tab(self, tab_id, option=None, **kw):
  661. """Query or modify the options of the specific tab_id.
  662. If kw is not given, returns a dict of the tab option values. If option
  663. is specified, returns the value of that option. Otherwise, sets the
  664. options to the corresponding values."""
  665. if option is not None:
  666. kw[option] = None
  667. return _val_or_dict(kw, self.tk.call, self._w, "tab", tab_id)
  668. def tabs(self):
  669. """Returns a list of windows managed by the notebook."""
  670. return self.tk.call(self._w, "tabs") or ()
  671. def enable_traversal(self):
  672. """Enable keyboard traversal for a toplevel window containing
  673. this notebook.
  674. This will extend the bindings for the toplevel window containing
  675. this notebook as follows:
  676. Control-Tab: selects the tab following the currently selected
  677. one
  678. Shift-Control-Tab: selects the tab preceding the currently
  679. selected one
  680. Alt-K: where K is the mnemonic (underlined) character of any
  681. tab, will select that tab.
  682. Multiple notebooks in a single toplevel may be enabled for
  683. traversal, including nested notebooks. However, notebook traversal
  684. only works properly if all panes are direct children of the
  685. notebook."""
  686. # The only, and good, difference I see is about mnemonics, which works
  687. # after calling this method. Control-Tab and Shift-Control-Tab always
  688. # works (here at least).
  689. self.tk.call("ttk::notebook::enableTraversal", self._w)
  690. class Panedwindow(Widget, Tkinter.PanedWindow):
  691. """Ttk Panedwindow widget displays a number of subwindows, stacked
  692. either vertically or horizontally."""
  693. def __init__(self, master=None, **kw):
  694. """Construct a Ttk Panedwindow with parent master.
  695. STANDARD OPTIONS
  696. class, cursor, style, takefocus
  697. WIDGET-SPECIFIC OPTIONS
  698. orient, width, height
  699. PANE OPTIONS
  700. weight
  701. """
  702. Widget.__init__(self, master, "ttk::panedwindow", kw)
  703. forget = Tkinter.PanedWindow.forget # overrides Pack.forget
  704. def insert(self, pos, child, **kw):
  705. """Inserts a pane at the specified positions.
  706. pos is either the string end, and integer index, or the name
  707. of a child. If child is already managed by the paned window,
  708. moves it to the specified position."""
  709. self.tk.call(self._w, "insert", pos, child, *(_format_optdict(kw)))
  710. def pane(self, pane, option=None, **kw):
  711. """Query or modify the options of the specified pane.
  712. pane is either an integer index or the name of a managed subwindow.
  713. If kw is not given, returns a dict of the pane option values. If
  714. option is specified then the value for that option is returned.
  715. Otherwise, sets the options to the corresponding values."""
  716. if option is not None:
  717. kw[option] = None
  718. return _val_or_dict(kw, self.tk.call, self._w, "pane", pane)
  719. def sashpos(self, index, newpos=None):
  720. """If newpos is specified, sets the position of sash number index.
  721. May adjust the positions of adjacent sashes to ensure that
  722. positions are monotonically increasing. Sash positions are further
  723. constrained to be between 0 and the total size of the widget.
  724. Returns the new position of sash number index."""
  725. return self.tk.call(self._w, "sashpos", index, newpos)
  726. PanedWindow = Panedwindow # Tkinter name compatibility
  727. class Progressbar(Widget):
  728. """Ttk Progressbar widget shows the status of a long-running
  729. operation. They can operate in two modes: determinate mode shows the
  730. amount completed relative to the total amount of work to be done, and
  731. indeterminate mode provides an animated display to let the user know
  732. that something is happening."""
  733. def __init__(self, master=None, **kw):
  734. """Construct a Ttk Progressbar with parent master.
  735. STANDARD OPTIONS
  736. class, cursor, style, takefocus
  737. WIDGET-SPECIFIC OPTIONS
  738. orient, length, mode, maximum, value, variable, phase
  739. """
  740. Widget.__init__(self, master, "ttk::progressbar", kw)
  741. def start(self, interval=None):
  742. """Begin autoincrement mode: schedules a recurring timer event
  743. that calls method step every interval milliseconds.
  744. interval defaults to 50 milliseconds (20 steps/second) if ommited."""
  745. self.tk.call(self._w, "start", interval)
  746. def step(self, amount=None):
  747. """Increments the value option by amount.
  748. amount defaults to 1.0 if omitted."""
  749. self.tk.call(self._w, "step", amount)
  750. def stop(self):
  751. """Stop autoincrement mode: cancels any recurring timer event
  752. initiated by start."""
  753. self.tk.call(self._w, "stop")
  754. class Radiobutton(Widget):
  755. """Ttk Radiobutton widgets are used in groups to show or change a
  756. set of mutually-exclusive options."""
  757. def __init__(self, master=None, **kw):
  758. """Construct a Ttk Radiobutton with parent master.
  759. STANDARD OPTIONS
  760. class, compound, cursor, image, state, style, takefocus,
  761. text, textvariable, underline, width
  762. WIDGET-SPECIFIC OPTIONS
  763. command, value, variable
  764. """
  765. Widget.__init__(self, master, "ttk::radiobutton", kw)
  766. def invoke(self):
  767. """Sets the option variable to the option value, selects the
  768. widget, and invokes the associated command.
  769. Returns the result of the command, or an empty string if
  770. no command is specified."""
  771. return self.tk.call(self._w, "invoke")
  772. class Scale(Widget, Tkinter.Scale):
  773. """Ttk Scale widget is typically used to control the numeric value of
  774. a linked variable that varies uniformly over some range."""
  775. def __init__(self, master=None, **kw):
  776. """Construct a Ttk Scale with parent master.
  777. STANDARD OPTIONS
  778. class, cursor, style, takefocus
  779. WIDGET-SPECIFIC OPTIONS
  780. command, from, length, orient, to, value, variable
  781. """
  782. Widget.__init__(self, master, "ttk::scale", kw)
  783. def configure(self, cnf=None, **kw):
  784. """Modify or query scale options.
  785. Setting a value for any of the "from", "from_" or "to" options
  786. generates a <<RangeChanged>> event."""
  787. if cnf:
  788. kw.update(cnf)
  789. Widget.configure(self, **kw)
  790. if any(['from' in kw, 'from_' in kw, 'to' in kw]):
  791. self.event_generate('<<RangeChanged>>')
  792. def get(self, x=None, y=None):
  793. """Get the current value of the value option, or the value
  794. corresponding to the coordinates x, y if they are specified.
  795. x and y are pixel coordinates relative to the scale widget
  796. origin."""
  797. return self.tk.call(self._w, 'get', x, y)
  798. class Scrollbar(Widget, Tkinter.Scrollbar):
  799. """Ttk Scrollbar controls the viewport of a scrollable widget."""
  800. def __init__(self, master=None, **kw):
  801. """Construct a Ttk Scrollbar with parent master.
  802. STANDARD OPTIONS
  803. class, cursor, style, takefocus
  804. WIDGET-SPECIFIC OPTIONS
  805. command, orient
  806. """
  807. Widget.__init__(self, master, "ttk::scrollbar", kw)
  808. class Separator(Widget):
  809. """Ttk Separator widget displays a horizontal or vertical separator
  810. bar."""
  811. def __init__(self, master=None, **kw):
  812. """Construct a Ttk Separator with parent master.
  813. STANDARD OPTIONS
  814. class, cursor, style, takefocus
  815. WIDGET-SPECIFIC OPTIONS
  816. orient
  817. """
  818. Widget.__init__(self, master, "ttk::separator", kw)
  819. class Sizegrip(Widget):
  820. """Ttk Sizegrip allows the user to resize the containing toplevel
  821. window by pressing and dragging the grip."""
  822. def __init__(self, master=None, **kw):
  823. """Construct a Ttk Sizegrip with parent master.
  824. STANDARD OPTIONS
  825. class, cursor, state, style, takefocus
  826. """
  827. Widget.__init__(self, master, "ttk::sizegrip", kw)
  828. class Treeview(Widget, Tkinter.XView, Tkinter.YView):
  829. """Ttk Treeview widget displays a hierarchical collection of items.
  830. Each item has a textual label, an optional image, and an optional list
  831. of data values. The data values are displayed in successive columns
  832. after the tree label."""
  833. def __init__(self, master=None, **kw):
  834. """Construct a Ttk Treeview with parent master.
  835. STANDARD OPTIONS
  836. class, cursor, style, takefocus, xscrollcommand,
  837. yscrollcommand
  838. WIDGET-SPECIFIC OPTIONS
  839. columns, displaycolumns, height, padding, selectmode, show
  840. ITEM OPTIONS
  841. text, image, values, open, tags
  842. TAG OPTIONS
  843. foreground, background, font, image
  844. """
  845. Widget.__init__(self, master, "ttk::treeview", kw)
  846. def bbox(self, item, column=None):
  847. """Returns the bounding box (relative to the treeview widget's
  848. window) of the specified item in the form x y width height.
  849. If column is specified, returns the bounding box of that cell.
  850. If the item is not visible (i.e., if it is a descendant of a
  851. closed item or is scrolled offscreen), returns an empty string."""
  852. return self.tk.call(self._w, "bbox", item, column)
  853. def get_children(self, item=None):
  854. """Returns a tuple of children belonging to item.
  855. If item is not specified, returns root children."""
  856. return self.tk.call(self._w, "children", item or '') or ()
  857. def set_children(self, item, *newchildren):
  858. """Replaces item's child with newchildren.
  859. Children present in item that are not present in newchildren
  860. are detached from tree. No items in newchildren may be an
  861. ancestor of item."""
  862. self.tk.call(self._w, "children", item, newchildren)
  863. def column(self, column, option=None, **kw):
  864. """Query or modify the options for the specified column.
  865. If kw is not given, returns a dict of the column option values. If
  866. option is specified then the value for that option is returned.
  867. Otherwise, sets the options to the corresponding values."""
  868. if option is not None:
  869. kw[option] = None
  870. return _val_or_dict(kw, self.tk.call, self._w, "column", column)
  871. def delete(self, *items):
  872. """Delete all specified items and all their descendants. The root
  873. item may not be deleted."""
  874. self.tk.call(self._w, "delete", items)
  875. def detach(self, *items):
  876. """Unlinks all of the specified items from the tree.
  877. The items and all of their descendants are still present, and may
  878. be reinserted at another point in the tree, but will not be
  879. displayed. The root item may not be detached."""
  880. self.tk.call(self._w, "detach", items)
  881. def exists(self, item):
  882. """Returns True if the specified item is present in the three,
  883. False otherwise."""
  884. return bool(self.tk.call(self._w, "exists", item))
  885. def focus(self, item=None):
  886. """If item is specified, sets the focus item to item. Otherwise,
  887. returns the current focus item, or '' if there is none."""
  888. return self.tk.call(self._w, "focus", item)
  889. def heading(self, column, option=None, **kw):
  890. """Query or modify the heading options for the specified column.
  891. If kw is not given, returns a dict of the heading option values. If
  892. option is specified then the value for that option is returned.
  893. Otherwise, sets the options to the corresponding values.
  894. Valid options/values are:
  895. text: text
  896. The text to display in the column heading
  897. image: image_name
  898. Specifies an image to display to the right of the column
  899. heading
  900. anchor: anchor
  901. Specifies how the heading text should be aligned. One of
  902. the standard Tk anchor values
  903. command: callback
  904. A callback to be invoked when the heading label is
  905. pressed.
  906. To configure the tree column heading, call this with column = "#0" """
  907. cmd = kw.get('command')
  908. if cmd and not isinstance(cmd, basestring):
  909. # callback not registered yet, do it now
  910. kw['command'] = self.master.register(cmd, self._substitute)
  911. if option is not None:
  912. kw[option] = None
  913. return _val_or_dict(kw, self.tk.call, self._w, 'heading', column)
  914. def identify(self, component, x, y):
  915. """Returns a description of the specified component under the
  916. point given by x and y, or the empty string if no such component
  917. is present at that position."""
  918. return self.tk.call(self._w, "identify", component, x, y)
  919. def identify_row(self, y):
  920. """Returns the item ID of the item at position y."""
  921. return self.identify("row", 0, y)
  922. def identify_column(self, x):
  923. """Returns the data column identifier of the cell at position x.
  924. The tree column has ID #0."""
  925. return self.identify("column", x, 0)
  926. def identify_region(self, x, y):
  927. """Returns one of:
  928. heading: Tree heading area.
  929. separator: Space between two columns headings;
  930. tree: The tree area.
  931. cell: A data cell.
  932. * Availability: Tk 8.6"""
  933. return self.identify("region", x, y)
  934. def identify_element(self, x, y):
  935. """Returns the element at position x, y.
  936. * Availability: Tk 8.6"""
  937. return self.identify("element", x, y)
  938. def index(self, item):
  939. """Returns the integer index of item within its parent's list
  940. of children."""
  941. return self.tk.call(self._w, "index", item)
  942. def insert(self, parent, index, iid=None, **kw):
  943. """Creates a new item and return the item identifier of the newly
  944. created item.
  945. parent is the item ID of the parent item, or the empty string
  946. to create a new top-level item. index is an integer, or the value
  947. end, specifying where in the list of parent's children to insert
  948. the new item. If index is less than or equal to zero, the new node
  949. is inserted at the beginning, if index is greater than or equal to
  950. the current number of children, it is inserted at the end. If iid
  951. is specified, it is used as the item identifier, iid must not
  952. already exist in the tree. Otherwise, a new unique identifier
  953. is generated."""
  954. opts = _format_optdict(kw)
  955. if iid:
  956. res = self.tk.call(self._w, "insert", parent, index,
  957. "-id", iid, *opts)
  958. else:
  959. res = self.tk.call(self._w, "insert", parent, index, *opts)
  960. return res
  961. def item(self, item, option=None, **kw):
  962. """Query or modify the options for the specified item.
  963. If no options are given, a dict with options/values for the item
  964. is returned. If option is specified then the value for that option
  965. is returned. Otherwise, sets the options to the corresponding
  966. values as given by kw."""
  967. if option is not None:
  968. kw[option] = None
  969. return _val_or_dict(kw, self.tk.call, self._w, "item", item)
  970. def move(self, item, parent, index):
  971. """Moves item to position index in parent's list of children.
  972. It is illegal to move an item under one of its descendants. If
  973. index is less than or equal to zero, item is moved to the
  974. beginning, if greater than or equal to the number of children,
  975. it is moved to the end. If item was detached it is reattached."""
  976. self.tk.call(self._w, "move", item, parent, index)
  977. reattach = move # A sensible method name for reattaching detached items
  978. def next(self, item):
  979. """Returns the identifier of item's next sibling, or '' if item
  980. is the last child of its parent."""
  981. return self.tk.call(self._w, "next", item)
  982. def parent(self, item):
  983. """Returns the ID of the parent of item, or '' if item is at the
  984. top level of the hierarchy."""
  985. return self.tk.call(self._w, "parent", item)
  986. def prev(self, item):
  987. """Returns the identifier of item's previous sibling, or '' if
  988. item is the first child of its parent."""
  989. return self.tk.call(self._w, "prev", item)
  990. def see(self, item):
  991. """Ensure that item is visible.
  992. Sets all of item's ancestors open option to True, and scrolls
  993. the widget if necessary so that item is within the visible
  994. portion of the tree."""
  995. self.tk.call(self._w, "see", item)
  996. def selection(self, selop=None, items=None):
  997. """If selop is not specified, returns selected items."""
  998. return self.tk.call(self._w, "selection", selop, items)
  999. def selection_set(self, items):
  1000. """items becomes the new selection."""
  1001. self.selection("set", items)
  1002. def selection_add(self, items):
  1003. """Add items to the selection."""
  1004. self.selection("add", items)
  1005. def selection_remove(self, items):
  1006. """Remove items from the selection."""
  1007. self.selection("remove", items)
  1008. def selection_toggle(self, items):
  1009. """Toggle the selection state of each item in items."""
  1010. self.selection("toggle", items)
  1011. def set(self, item, column=None, value=None):
  1012. """With one argument, returns a dictionary of column/value pairs
  1013. for the specified item. With two arguments, returns the current
  1014. value of the specified column. With three arguments, sets the
  1015. value of given column in given item to the specified value."""
  1016. res = self.tk.call(self._w, "set", item, column, value)
  1017. if column is None and value is None:
  1018. return _dict_from_tcltuple(res, False)
  1019. else:
  1020. return res
  1021. def tag_bind(self, tagname, sequence=None, callback=None):
  1022. """Bind a callback for the given event sequence to the tag tagname.
  1023. When an event is delivered to an item, the callbacks for each
  1024. of the

Large files files are truncated, but you can click here to view the full file