ttk.py 56 KB

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