ttk.py 55 KB

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