Back to index

python3.2  3.2.2
Classes | Functions | Variables
tkinter.ttk Namespace Reference

Classes

class  Style
class  Widget
class  Button
class  Checkbutton
class  Entry
class  Combobox
class  Frame
class  Label
class  Labelframe
class  Menubutton
class  Notebook
class  Panedwindow
class  Progressbar
class  Radiobutton
class  Scale
class  Scrollbar
class  Separator
class  Sizegrip
class  Treeview
class  LabeledScale
class  OptionMenu

Functions

def _load_tile
def _format_optdict
def _format_mapdict
def _format_elemcreate
def _format_layoutlist
def _script_from_settings
def _dict_from_tcltuple
def _list_from_statespec
def _list_from_layouttuple
def _val_or_dict
def _convert_stringval
def tclobjs_to_py
def setup_master

Variables

string __version__ = "0.3.1"
string __author__ = "Guilherme Polo <ggpolo@gmail.com>"
list __all__
 _flatten = tkinter._flatten
float _REQUIRE_TILE = 8.5
 LabelFrame = Labelframe
 PanedWindow = Panedwindow

Detailed Description

Ttk wrapper.

This module provides classes to allow using Tk themed widget set.

Ttk is based on a revised and enhanced version of
TIP #48 (http://tip.tcl.tk/48) specified style engine.

Its basic idea is to separate, to the extent possible, the code
implementing a widget's behavior from the code implementing its
appearance. Widget class bindings are primarily responsible for
maintaining the widget state and invoking callbacks, all aspects
of the widgets appearance lies at Themes.

Function Documentation

def tkinter.ttk._convert_stringval (   value) [private]
Converts a value to, hopefully, a more appropriate Python object.

Definition at line 325 of file ttk.py.

00325 
00326 def _convert_stringval(value):
00327     """Converts a value to, hopefully, a more appropriate Python object."""
00328     value = str(value)
00329     try:
00330         value = int(value)
00331     except (ValueError, TypeError):
00332         pass
00333 
00334     return value

Here is the caller graph for this function:

def tkinter.ttk._dict_from_tcltuple (   ttuple,
  cut_minus = True 
) [private]
Break tuple in pairs, format it properly, then build the return
dict. If cut_minus is True, the supposed '-' prefixing options will
be removed.

ttuple is expected to contain an even number of elements.

Definition at line 250 of file ttk.py.

00250 
00251 def _dict_from_tcltuple(ttuple, cut_minus=True):
00252     """Break tuple in pairs, format it properly, then build the return
00253     dict. If cut_minus is True, the supposed '-' prefixing options will
00254     be removed.
00255 
00256     ttuple is expected to contain an even number of elements."""
00257     opt_start = 1 if cut_minus else 0
00258 
00259     retdict = {}
00260     it = iter(ttuple)
00261     for opt, val in zip(it, it):
00262         retdict[str(opt)[opt_start:]] = val
00263 
00264     return tclobjs_to_py(retdict)

Here is the call graph for this function:

Here is the caller graph for this function:

def tkinter.ttk._format_elemcreate (   etype,
  script = False,
  args,
  kw 
) [private]
Formats args and kw according to the given element factory etype.

Definition at line 122 of file ttk.py.

00122 
00123 def _format_elemcreate(etype, script=False, *args, **kw):
00124     """Formats args and kw according to the given element factory etype."""
00125     spec = None
00126     opts = ()
00127     if etype in ("image", "vsapi"):
00128         if etype == "image": # define an element based on an image
00129             # first arg should be the default image name
00130             iname = args[0]
00131             # next args, if any, are statespec/value pairs which is almost
00132             # a mapdict, but we just need the value
00133             imagespec = _format_mapdict({None: args[1:]})[1]
00134             spec = "%s %s" % (iname, imagespec)
00135 
00136         else:
00137             # define an element whose visual appearance is drawn using the
00138             # Microsoft Visual Styles API which is responsible for the
00139             # themed styles on Windows XP and Vista.
00140             # Availability: Tk 8.6, Windows XP and Vista.
00141             class_name, part_id = args[:2]
00142             statemap = _format_mapdict({None: args[2:]})[1]
00143             spec = "%s %s %s" % (class_name, part_id, statemap)
00144 
00145         opts = _format_optdict(kw, script)
00146 
00147     elif etype == "from": # clone an element
00148         # it expects a themename and optionally an element to clone from,
00149         # otherwise it will clone {} (empty element)
00150         spec = args[0] # theme name
00151         if len(args) > 1: # elementfrom specified
00152             opts = (args[1], )
00153 
00154     if script:
00155         spec = '{%s}' % spec
00156         opts = ' '.join(map(str, opts))
00157 
00158     return spec, opts

Here is the call graph for this function:

Here is the caller graph for this function:

def tkinter.ttk._format_layoutlist (   layout,
  indent = 0,
  indent_size = 2 
) [private]
Formats a layout list so we can pass the result to ttk::style
layout and ttk::style settings. Note that the layout doesn't has to
be a list necessarily.

E.g.:
  [("Menubutton.background", None),
   ("Menubutton.button", {"children":
       [("Menubutton.focus", {"children":
           [("Menubutton.padding", {"children":
            [("Menubutton.label", {"side": "left", "expand": 1})]
           })]
       })]
   }),
   ("Menubutton.indicator", {"side": "right"})
  ]

  returns:

  Menubutton.background
  Menubutton.button -children {
    Menubutton.focus -children {
      Menubutton.padding -children {
        Menubutton.label -side left -expand 1
      }
    }
  }
  Menubutton.indicator -side right

Definition at line 159 of file ttk.py.

00159 
00160 def _format_layoutlist(layout, indent=0, indent_size=2):
00161     """Formats a layout list so we can pass the result to ttk::style
00162     layout and ttk::style settings. Note that the layout doesn't has to
00163     be a list necessarily.
00164 
00165     E.g.:
00166       [("Menubutton.background", None),
00167        ("Menubutton.button", {"children":
00168            [("Menubutton.focus", {"children":
00169                [("Menubutton.padding", {"children":
00170                 [("Menubutton.label", {"side": "left", "expand": 1})]
00171                })]
00172            })]
00173        }),
00174        ("Menubutton.indicator", {"side": "right"})
00175       ]
00176 
00177       returns:
00178 
00179       Menubutton.background
00180       Menubutton.button -children {
00181         Menubutton.focus -children {
00182           Menubutton.padding -children {
00183             Menubutton.label -side left -expand 1
00184           }
00185         }
00186       }
00187       Menubutton.indicator -side right"""
00188     script = []
00189 
00190     for layout_elem in layout:
00191         elem, opts = layout_elem
00192         opts = opts or {}
00193         fopts = ' '.join(map(str, _format_optdict(opts, True, "children")))
00194         head = "%s%s%s" % (' ' * indent, elem, (" %s" % fopts) if fopts else '')
00195 
00196         if "children" in opts:
00197             script.append(head + " -children {")
00198             indent += indent_size
00199             newscript, indent = _format_layoutlist(opts['children'], indent,
00200                 indent_size)
00201             script.append(newscript)
00202             indent -= indent_size
00203             script.append('%s}' % (' ' * indent))
00204         else:
00205             script.append(head)
00206 
00207     return '\n'.join(script), indent

Here is the call graph for this function:

Here is the caller graph for this function:

def tkinter.ttk._format_mapdict (   mapdict,
  script = False 
) [private]
Formats mapdict to pass it to tk.call.

E.g. (script=False):
  {'expand': [('active', 'selected', 'grey'), ('focus', [1, 2, 3, 4])]}

  returns:

  ('-expand', '{active selected} grey focus {1, 2, 3, 4}')

Definition at line 84 of file ttk.py.

00084 
00085 def _format_mapdict(mapdict, script=False):
00086     """Formats mapdict to pass it to tk.call.
00087 
00088     E.g. (script=False):
00089       {'expand': [('active', 'selected', 'grey'), ('focus', [1, 2, 3, 4])]}
00090 
00091       returns:
00092 
00093       ('-expand', '{active selected} grey focus {1, 2, 3, 4}')"""
00094     # if caller passes a Tcl script to tk.call, all the values need to
00095     # be grouped into words (arguments to a command in Tcl dialect)
00096     format = "%s" if not script else "{%s}"
00097 
00098     opts = []
00099     for opt, value in mapdict.items():
00100 
00101         opt_val = []
00102         # each value in mapdict is expected to be a sequence, where each item
00103         # is another sequence containing a state (or several) and a value
00104         for statespec in value:
00105             state, val = statespec[:-1], statespec[-1]
00106 
00107             if len(state) > 1: # group multiple states
00108                 state = "{%s}" % ' '.join(state)
00109             else: # single state
00110                 # if it is empty (something that evaluates to False), then
00111                 # format it to Tcl code to denote the "normal" state
00112                 state = state[0] or '{}'
00113 
00114             if isinstance(val, (list, tuple)): # val needs to be grouped
00115                 val = "{%s}" % ' '.join(map(str, val))
00116 
00117             opt_val.append("%s %s" % (state, val))
00118 
00119         opts.append(("-%s" % opt, format % ' '.join(opt_val)))
00120 
00121     return _flatten(opts)

Here is the caller graph for this function:

def tkinter.ttk._format_optdict (   optdict,
  script = False,
  ignore = None 
) [private]
Formats optdict to a tuple to pass it to tk.call.

E.g. (script=False):
  {'foreground': 'blue', 'padding': [1, 2, 3, 4]} returns:
  ('-foreground', 'blue', '-padding', '1 2 3 4')

Definition at line 50 of file ttk.py.

00050 
00051 def _format_optdict(optdict, script=False, ignore=None):
00052     """Formats optdict to a tuple to pass it to tk.call.
00053 
00054     E.g. (script=False):
00055       {'foreground': 'blue', 'padding': [1, 2, 3, 4]} returns:
00056       ('-foreground', 'blue', '-padding', '1 2 3 4')"""
00057     format = "%s" if not script else "{%s}"
00058 
00059     opts = []
00060     for opt, value in optdict.items():
00061         if ignore and opt in ignore:
00062             continue
00063 
00064         if isinstance(value, (list, tuple)):
00065             v = []
00066             for val in value:
00067                 if isinstance(val, str):
00068                     v.append(str(val) if val else '{}')
00069                 else:
00070                     v.append(str(val))
00071 
00072             # format v according to the script option, but also check for
00073             # space in any value in v in order to group them correctly
00074             value = format % ' '.join(
00075                 ('{%s}' if ' ' in val else '%s') % val for val in v)
00076 
00077         if script and value == '':
00078             value = '{}' # empty string in Python is equivalent to {} in Tcl
00079 
00080         opts.append(("-%s" % opt, value))
00081 
00082     # Remember: _flatten skips over None
00083     return _flatten(opts)

Here is the caller graph for this function:

def tkinter.ttk._list_from_layouttuple (   ltuple) [private]
Construct a list from the tuple returned by ttk::layout, this is
somewhat the reverse of _format_layoutlist.

Definition at line 282 of file ttk.py.

00282 
00283 def _list_from_layouttuple(ltuple):
00284     """Construct a list from the tuple returned by ttk::layout, this is
00285     somewhat the reverse of _format_layoutlist."""
00286     res = []
00287 
00288     indx = 0
00289     while indx < len(ltuple):
00290         name = ltuple[indx]
00291         opts = {}
00292         res.append((name, opts))
00293         indx += 1
00294 
00295         while indx < len(ltuple): # grab name's options
00296             opt, val = ltuple[indx:indx + 2]
00297             if not opt.startswith('-'): # found next name
00298                 break
00299 
00300             opt = opt[1:] # remove the '-' from the option
00301             indx += 2
00302 
00303             if opt == 'children':
00304                 val = _list_from_layouttuple(val)
00305 
00306             opts[opt] = val
00307 
00308     return res

Here is the caller graph for this function:

def tkinter.ttk._list_from_statespec (   stuple) [private]
Construct a list from the given statespec tuple according to the
accepted statespec accepted by _format_mapdict.

Definition at line 265 of file ttk.py.

00265 
00266 def _list_from_statespec(stuple):
00267     """Construct a list from the given statespec tuple according to the
00268     accepted statespec accepted by _format_mapdict."""
00269     nval = []
00270     for val in stuple:
00271         typename = getattr(val, 'typename', None)
00272         if typename is None:
00273             nval.append(val)
00274         else: # this is a Tcl object
00275             val = str(val)
00276             if typename == 'StateSpec':
00277                 val = val.split()
00278             nval.append(val)
00279 
00280     it = iter(nval)
00281     return [_flatten(spec) for spec in zip(it, it)]

Here is the call graph for this function:

Here is the caller graph for this function:

def tkinter.ttk._load_tile (   master) [private]

Definition at line 35 of file ttk.py.

00035 
00036 def _load_tile(master):
00037     if _REQUIRE_TILE:
00038         import os
00039         tilelib = os.environ.get('TILE_LIBRARY')
00040         if tilelib:
00041             # append custom tile path to the the list of directories that
00042             # Tcl uses when attempting to resolve packages with the package
00043             # command
00044             master.tk.eval(
00045                     'global auto_path; '
00046                     'lappend auto_path {%s}' % tilelib)
00047 
00048         master.tk.eval('package require tile') # TclError may be raised here
00049         master._tile_loaded = True

Here is the caller graph for this function:

def tkinter.ttk._script_from_settings (   settings) [private]
Returns an appropriate script, based on settings, according to
theme_settings definition to be used by theme_settings and
theme_create.

Definition at line 208 of file ttk.py.

00208 
00209 def _script_from_settings(settings):
00210     """Returns an appropriate script, based on settings, according to
00211     theme_settings definition to be used by theme_settings and
00212     theme_create."""
00213     script = []
00214     # a script will be generated according to settings passed, which
00215     # will then be evaluated by Tcl
00216     for name, opts in settings.items():
00217         # will format specific keys according to Tcl code
00218         if opts.get('configure'): # format 'configure'
00219             s = ' '.join(map(str, _format_optdict(opts['configure'], True)))
00220             script.append("ttk::style configure %s %s;" % (name, s))
00221 
00222         if opts.get('map'): # format 'map'
00223             s = ' '.join(map(str, _format_mapdict(opts['map'], True)))
00224             script.append("ttk::style map %s %s;" % (name, s))
00225 
00226         if 'layout' in opts: # format 'layout' which may be empty
00227             if not opts['layout']:
00228                 s = 'null' # could be any other word, but this one makes sense
00229             else:
00230                 s, _ = _format_layoutlist(opts['layout'])
00231             script.append("ttk::style layout %s {\n%s\n}" % (name, s))
00232 
00233         if opts.get('element create'): # format 'element create'
00234             eopts = opts['element create']
00235             etype = eopts[0]
00236 
00237             # find where args end, and where kwargs start
00238             argc = 1 # etype was the first one
00239             while argc < len(eopts) and not hasattr(eopts[argc], 'items'):
00240                 argc += 1
00241 
00242             elemargs = eopts[1:argc]
00243             elemkw = eopts[argc] if argc < len(eopts) and eopts[argc] else {}
00244             spec, opts = _format_elemcreate(etype, True, *elemargs, **elemkw)
00245 
00246             script.append("ttk::style element create %s %s %s %s" % (
00247                 name, etype, spec, opts))
00248 
00249     return '\n'.join(script)

Here is the call graph for this function:

Here is the caller graph for this function:

def tkinter.ttk._val_or_dict (   options,
  func,
  args 
) [private]
Format options then call func with args and options and return
the appropriate result.

If no option is specified, a dict is returned. If a option is
specified with the None value, the value for that option is returned.
Otherwise, the function just sets the passed options and the caller
shouldn't be expecting a return value anyway.

Definition at line 309 of file ttk.py.

00309 
00310 def _val_or_dict(options, func, *args):
00311     """Format options then call func with args and options and return
00312     the appropriate result.
00313 
00314     If no option is specified, a dict is returned. If a option is
00315     specified with the None value, the value for that option is returned.
00316     Otherwise, the function just sets the passed options and the caller
00317     shouldn't be expecting a return value anyway."""
00318     options = _format_optdict(options)
00319     res = func(*(args + options))
00320 
00321     if len(options) % 2: # option specified without a value, return its value
00322         return res
00323 
00324     return _dict_from_tcltuple(res)

Here is the call graph for this function:

Here is the caller graph for this function:

def tkinter.ttk.setup_master (   master = None)
If master is not None, itself is returned. If master is None,
the default master is returned if there is one, otherwise a new
master is created and returned.

If it is not allowed to use the default root and master is None,
RuntimeError is raised.

Definition at line 352 of file ttk.py.

00352 
00353 def setup_master(master=None):
00354     """If master is not None, itself is returned. If master is None,
00355     the default master is returned if there is one, otherwise a new
00356     master is created and returned.
00357 
00358     If it is not allowed to use the default root and master is None,
00359     RuntimeError is raised."""
00360     if master is None:
00361         if tkinter._support_default_root:
00362             master = tkinter._default_root or tkinter.Tk()
00363         else:
00364             raise RuntimeError(
00365                     "No master specified and tkinter is "
00366                     "configured to not support default root")
00367     return master
00368 

Here is the caller graph for this function:

def tkinter.ttk.tclobjs_to_py (   adict)
Returns adict with its values converted from Tcl objects to Python
objects.

Definition at line 335 of file ttk.py.

00335 
00336 def tclobjs_to_py(adict):
00337     """Returns adict with its values converted from Tcl objects to Python
00338     objects."""
00339     for opt, val in adict.items():
00340         if val and hasattr(val, '__len__') and not isinstance(val, str):
00341             if getattr(val[0], 'typename', None) == 'StateSpec':
00342                 val = _list_from_statespec(val)
00343             else:
00344                 val = list(map(_convert_stringval, val))
00345 
00346         elif hasattr(val, 'typename'): # some other (single) Tcl object
00347             val = _convert_stringval(val)
00348 
00349         adict[opt] = val
00350 
00351     return adict

Here is the call graph for this function:

Here is the caller graph for this function:


Variable Documentation

Initial value:
00001 ["Button", "Checkbutton", "Combobox", "Entry", "Frame", "Label",
00002            "Labelframe", "LabelFrame", "Menubutton", "Notebook", "Panedwindow",
00003            "PanedWindow", "Progressbar", "Radiobutton", "Scale", "Scrollbar",
00004            "Separator", "Sizegrip", "Style", "Treeview",
00005            # Extensions
00006            "LabeledScale", "OptionMenu",
00007            # functions
00008            "tclobjs_to_py", "setup_master"]

Definition at line 19 of file ttk.py.

string tkinter.ttk.__author__ = "Guilherme Polo <ggpolo@gmail.com>"

Definition at line 17 of file ttk.py.

Definition at line 15 of file ttk.py.

Definition at line 30 of file ttk.py.

Definition at line 33 of file ttk.py.

Definition at line 801 of file ttk.py.

Definition at line 1012 of file ttk.py.