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 tk48 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 extensions functions internal function if script if caller passes a tcl script to tk call all the values need to be grouped into words arguments to a command in tcl dialect value stringifyvalue elif isinstancevalue list tuple value joinvalue return value def formatoptdictoptdict scriptfalse ignorenone each value in mapdict is expected to be a sequence where each item is another sequence containing a state or several and a value e g scriptfalse active selected grey focus 1 2 3 4 returns active selected grey focus 1 2 3 4 if it is empty something that evaluates to false then format it to tcl code to denote the normal state group multiple states formats mapdict to pass it to tk call e g scriptfalse expand active selected grey focus 1 2 3 4 returns expand active selected grey focus 1 2 3 4 opts for opt value in mapdict items opts extends opt formatoptvaluemapdictvaluesvalue script return flattenopts def formatelemcreateetype scriptfalse args kw first arg should be the default image name next args if any are statespecvalue pairs which is almost a mapdict but we just need the value define an element whose visual appearance is drawn using the microsoft visual styles api which is responsible for the themed styles on windows xp and vista availability tk 8 6 windows xp and vista it expects a themename and optionally an element to clone from otherwise it will clone empty element formats a layout list so we can pass the result to ttk style layout and ttk style settings note that the layout doesn t have 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 script for layoutelem in layout elem opts layoutelem opts opts or fopts joinformatoptdictopts true children head sss indent elem s fopts if fopts else if children in opts script appendhead children indent indentsize newscript indent formatlayoutlistopts children indent indentsize script appendnewscript indent indentsize script append s indent else script appendhead return n joinscript indent def scriptfromsettingssettings a script will be generated according to settings passed which will then be evaluated by tcl will format specific keys according to tcl code find where args end and where kwargs start construct a list from the given statespec tuple according to the accepted statespec accepted by formatmapdict if isinstancestuple str return stuple result it iterstuple for state val in zipit it if hasattrstate typename this is a tcl object state strstate split elif isinstancestate str state state split elif not isinstancestate tuple list state state if hasattrval typename val strval result appendstate val return result def listfromlayouttupletk ltuple format options then call tk command with args and options and return the appropriate result if no option is specified a dict is returned if an 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 options formatoptdictoptions res tk callargs options if lenoptions 2 option specified without a value return its value return res return splitdicttk res convtclobjtopy def convertstringvalvalue return value converted from tcl object to python object if val and hasattrval len and not isinstanceval str if getattrval0 typename none statespec val listfromstatespecval else val listmapconvertstringval val elif hasattrval typename some other single tcl object val convertstringvalval return val def tclobjstopyadict 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 if master is none master tkinter getdefaultroot return master class styleobject query or sets the default value of the specified options in style each key in kw is an option and each value is either a string or a sequence identifying the value for that option if queryopt is not none kwqueryopt none result valordictself tk kw self name configure style if result or queryopt return result def mapself style queryoptnone kw returns the value specified for option in style if state is specified it is expected to be a sequence of one or more states if the default argument is set it is used as a fallback value in case no specification for option is found state joinstate if state else return self tk callself name lookup style s option state default def layoutself style layoutspecnone when calling layoutstyle later create a new element in the current theme of given etype specs opts formatelemcreateetype false args kw self tk callself name element create elementname etype specs opts def elementnamesself return the list of elementname s options return tupleo lstrip for o in self tk splitlist self tk callself name element options elementname def themecreateself themename parentnone settingsnone temporarily sets the current theme to themename apply specified settings and then restore the previous theme each key in settings is a style and each value may contain the keys configure map layout and element create and they are expected to have the same format as specified by the methods configure map layout and elementcreate respectively script scriptfromsettingssettings self tk callself name theme settings themename script def themenamesself if themename is none returns the theme in use otherwise set the current theme to themename refreshes all widgets and emits a themechanged event if themename is none starting on tk 8 6 checking this global is no longer needed since it allows doing self tk callself name theme use return self tk evalreturn ttk currenttheme using ttk settheme instead of ttk style theme use causes the variable currenttheme to be updated also ttk settheme calls ttk style theme use in order to change theme self tk callttk settheme themename class widgettkinter widget constructs a ttk widget with the parent master standard options class cursor takefocus style scrollable widget options xscrollcommand yscrollcommand label widget options text textvariable underline image compound width widget states active disabled focus pressed selected background readonly alternate invalid returns the name of the element at position x y or the empty string if the point does not lie within any element x and y are pixel coordinates relative to the widget return self tk callself w identify x y def instateself statespec callbacknone args kw modify or inquire widget state widget state is returned if statespec is none otherwise it is set according to the statespec flags and then a new state spec is returned indicating which flags were changed statespec is expected to be a sequence if statespec is not none statespec joinstatespec return self tk splitliststrself tk callself w state statespec class buttonwidget construct a ttk button widget with the parent master standard options class compound cursor image state style takefocus text textvariable underline width widgetspecific options command default width invokes the command associated with the button return self tk callself w invoke class checkbuttonwidget construct a ttk checkbutton widget with the parent master standard options class compound cursor image state style takefocus text textvariable underline width widgetspecific options command offvalue onvalue variable toggles between the selected and deselected states and invokes the associated command if the widget is currently selected sets the option variable to the offvalue option and deselects the widget otherwise sets the option variable to the option onvalue returns the result of the associated command return self tk callself w invoke class entrywidget tkinter entry constructs a ttk entry widget with the parent master standard options class cursor style takefocus xscrollcommand widgetspecific options exportselection invalidcommand justify show state textvariable validate validatecommand width validation modes none key focus focusin focusout all return a tuple of x y width height which describes the bounding box of the character given by index return self getintsself tk callself w bbox index def identifyself x y force revalidation independent of the conditions specified by the validate option returns false if validation fails true if it succeeds sets or clears the invalid state accordingly return self tk getbooleanself tk callself w validate class comboboxentry construct a ttk combobox widget with the parent master standard options class cursor style takefocus widgetspecific options exportselection justify height postcommand state textvariable values width if newindex is supplied sets the combobox value to the element at position newindex in the list of values otherwise returns the index of the current value in the list of values or 1 if the current value does not appear in the list if newindex is none return self tk getintself tk callself w current return self tk callself w current newindex def setself value ttk frame widget is a container used to group other widgets together def initself masternone kw widget initself master ttk frame kw class labelwidget construct a ttk label with parent master standard options class compound cursor image style takefocus text textvariable underline width widgetspecific options anchor background font foreground justify padding relief text wraplength ttk labelframe widget is a container used to group other widgets together it has an optional label which may be a plain text string or another widget def initself masternone kw widget initself master ttk labelframe kw labelframe labelframe tkinter name compatibility class menubuttonwidget construct a ttk menubutton with parent master standard options class compound cursor image state style takefocus text textvariable underline width widgetspecific options direction menu ttk notebook widget manages a collection of windows and displays a single one at a time each child window is associated with a tab which the user may select to change the currentlydisplayed window def initself masternone kw widget initself master ttk notebook kw def addself child kw removes the tab specified by tabid unmaps and unmanages the associated window self tk callself w forget tabid def hideself tabid returns the name of the tab element at position x y or the empty string if none return self tk callself w identify x y def indexself tabid inserts a pane at the specified position pos is either the string end an integer index or the name of a managed child if child is already managed by the notebook moves it to the specified position self tk callself w insert pos child formatoptdictkw def selectself tabidnone query or modify the options of the specific tabid if kw is not given returns a dict of the tab option values if option is specified returns the value of that option otherwise sets the options to the corresponding values if option is not none kwoption none return valordictself tk kw self w tab tabid def tabsself enable keyboard traversal for a toplevel window containing this notebook this will extend the bindings for the toplevel window containing this notebook as follows controltab selects the tab following the currently selected one shiftcontroltab selects the tab preceding the currently selected one altk where k is the mnemonic underlined character of any tab will select that tab multiple notebooks in a single toplevel may be enabled for traversal including nested notebooks however notebook traversal only works properly if all panes are direct children of the notebook the only and good difference i see is about mnemonics which works after calling this method controltab and shiftcontroltab always works here at least self tk callttk notebook enabletraversal self w class panedwindowwidget tkinter panedwindow construct a ttk panedwindow with parent master standard options class cursor style takefocus widgetspecific options orient width height pane options weight inserts a pane at the specified positions pos is either the string end and integer index or the name of a child if child is already managed by the paned window moves it to the specified position self tk callself w insert pos child formatoptdictkw def paneself pane optionnone kw if newpos is specified sets the position of sash number index may adjust the positions of adjacent sashes to ensure that positions are monotonically increasing sash positions are further constrained to be between 0 and the total size of the widget returns the new position of sash number index return self tk getintself tk callself w sashpos index newpos panedwindow panedwindow tkinter name compatibility class progressbarwidget construct a ttk progressbar with parent master standard options class cursor style takefocus widgetspecific options orient length mode maximum value variable phase begin autoincrement mode schedules a recurring timer event that calls method step every interval milliseconds interval defaults to 50 milliseconds 20 stepssecond if omitted self tk callself w start interval def stepself amountnone stop autoincrement mode cancels any recurring timer event initiated by start self tk callself w stop class radiobuttonwidget construct a ttk radiobutton with parent master standard options class compound cursor image state style takefocus text textvariable underline width widgetspecific options command value variable sets the option variable to the option value selects the widget and invokes the associated command returns the result of the command or an empty string if no command is specified return self tk callself w invoke class scalewidget tkinter scale construct a ttk scale with parent master standard options class cursor style takefocus widgetspecific options command from length orient to value variable modify or query scale options setting a value for any of the from from or to options generates a rangechanged event retval widget configureself cnf kw if not isinstancecnf typenone str kw updatecnf if any from in kw from in kw to in kw self eventgenerate rangechanged return retval def getself xnone ynone ttk scrollbar controls the viewport of a scrollable widget def initself masternone kw widget initself master ttk scrollbar kw class separatorwidget construct a ttk separator with parent master standard options class cursor style takefocus widgetspecific options orient ttk sizegrip allows the user to resize the containing toplevel window by pressing and dragging the grip def initself masternone kw widget initself master ttk sizegrip kw class spinboxentry def initself masternone kw entry initself master ttk spinbox kw def setself value ttk treeview widget displays a hierarchical collection of items each item has a textual label an optional image and an optional list of data values the data values are displayed in successive columns after the tree label def initself masternone kw widget initself master ttk treeview kw def bboxself item columnnone returns a tuple of children belonging to item if item is not specified returns root children return self tk splitlist self tk callself w children item or or def setchildrenself item newchildren query or modify the options for the specified column if kw is not given returns a dict of the column option values if option is specified then the value for that option is returned otherwise sets the options to the corresponding values if option is not none kwoption none return valordictself tk kw self w column column def deleteself items unlinks all of the specified items from the tree the items and all of their descendants are still present and may be reinserted at another point in the tree but will not be displayed the root item may not be detached self tk callself w detach items def existsself item if item is specified sets the focus item to item otherwise returns the current focus item or if there is none return self tk callself w focus item def headingself column optionnone kw callback not registered yet do it now returns a description of the specified component under the point given by x and y or the empty string if no such component is present at that position return self tk callself w identify component x y def identifyrowself y returns the data column identifier of the cell at position x the tree column has id 0 return self identifycolumn x 0 def identifyregionself x y returns the element at position x y availability tk 8 6 return self identifyelement x y def indexself item creates a new item and return the item identifier of the newly created item parent is the item id of the parent item or the empty string to create a new toplevel item index is an integer or the value end specifying where in the list of parent s children to insert the new item if index is less than or equal to zero the new node is inserted at the beginning if index is greater than or equal to the current number of children it is inserted at the end if iid is specified it is used as the item identifier iid must not already exist in the tree otherwise a new unique identifier is generated opts formatoptdictkw if iid is not none res self tk callself w insert parent index id iid opts else res self tk callself w insert parent index opts return res def itemself item optionnone kw moves item to position index in parent s list of children it is illegal to move an item under one of its descendants if index is less than or equal to zero item is moved to the beginning if greater than or equal to the number of children it is moved to the end if item was detached it is reattached self tk callself w move item parent index reattach move a sensible method name for reattaching detached items def nextself item returns the id of the parent of item or if item is at the top level of the hierarchy return self tk callself w parent item def prevself item ensure that item is visible sets all of item s ancestors open option to true and scrolls the widget if necessary so that item is within the visible portion of the tree self tk callself w see item def selectionself the specified items becomes the new selection self selectionset items def selectionaddself items remove all of the specified items from the selection self selectionremove items def selectiontoggleself items query or set the value of given item with one argument return a dictionary of columnvalue pairs for the specified item with two arguments return the current value of the specified column with three arguments set the value of given column in given item to the specified value res self tk callself w set item column value if column is none and value is none return splitdictself tk res cutminusfalse convtclobjtopy else return res def tagbindself tagname sequencenone callbacknone query or modify the options for the specified tagname if kw is not given returns a dict of the option settings for tagname if option is specified returns the value for that option for the specified tagname otherwise sets the options to the corresponding values for the given tagname if option is not none kwoption none return valordictself tk kw self w tag configure tagname def taghasself tagname itemnone extensions a ttk scale widget with a ttk label widget indicating its current value the ttk scale can be accessed through instance scale and ttk label can be accessed through instance label def initself masternone variablenone from0 to10 kw self labeltop kw pop compound top top frame initself master kw self variable variable or tkinter intvarmaster self variable setfrom self lastvalid from self label labelself self scale scaleself variableself variable fromfrom toto self scale bind rangechanged self adjust position scale and label according to the compound option scaleside bottom if self labeltop else top labelside top if scaleside bottom else bottom self scale packsidescaleside fill x dummy required to make frame correct height dummy labelself dummy packsidelabelside dummy lower self label placeanchor n if labelside top else s update the label as scale or variable changes self tracecb self variable tracevariable w self adjust self bind configure self adjust self bind map self adjust def destroyself adjust the label position according to the scale def adjustlabel self updateidletasks force scale redraw x y self scale coords if self labeltop y self scale winfoy self label winforeqheight else y self scale winforeqheight self label winforeqheight self label placeconfigurexx yy from tonumberself scale from to tonumberself scale to if to from from to to from newval self variable get if not from newval to value outside range set value back to the last valid one self value self lastvalid return self lastvalid newval self label text newval self afteridleadjustlabel property def valueself set new scale value self variable setval class optionmenumenubutton construct a themed optionmenu widget with master as the parent the resource textvariable set to variable the initially selected value specified by the default parameter the menu values given by values and additional keywords widgetspecific options style stylename menubutton style direction above below left right or flush menubutton direction command callback a callback that will be invoked after selecting an item build a new menu of radiobuttons with values and optionally a default value menu self menu menu delete0 end for val in values menu addradiobuttonlabelval command none if self callback is none else lambda valval self callbackval variableself variable if default self variable setdefault def destroyself extensions functions internal function if caller passes a tcl script to tk call all the values need to be grouped into words arguments to a command in tcl dialect 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 each value in mapdict is expected to be a sequence where each item is another sequence containing a state or several and a value e g script false active selected grey focus 1 2 3 4 returns active selected grey focus 1 2 3 4 if it is empty something that evaluates to false then format it to tcl code to denote the normal state group multiple states raise typeerror if not str 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 formats args and kw according to the given element factory etype define an element based on an image first arg should be the default image name next args if any are statespec value pairs which is almost a mapdict but we just need the value define an element whose visual appearance is drawn using the microsoft visual styles api which is responsible for the themed styles on windows xp and vista availability tk 8 6 windows xp and vista clone an element it expects a themename and optionally an element to clone from otherwise it will clone empty element theme name elementfrom specified formats a layout list so we can pass the result to ttk style layout and ttk style settings note that the layout doesn t have 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 returns an appropriate script based on settings according to theme_settings definition to be used by theme_settings and theme_create a script will be generated according to settings passed which will then be evaluated by tcl will format specific keys according to tcl code format configure format map format layout which may be empty could be any other word but this one makes sense format element create find where args end and where kwargs start etype was the first one construct a list from the given statespec tuple according to the accepted statespec accepted by _format_mapdict this is a tcl object construct a list from the tuple returned by ttk layout this is somewhat the reverse of _format_layoutlist grab name s options found next name remove the from the option format options then call tk command with args and options and return the appropriate result if no option is specified a dict is returned if an 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 option specified without a value return its value converts a value to hopefully a more appropriate python object return value converted from tcl object to python object some other single tcl object returns adict with its values converted from tcl objects to python objects 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 manipulate style database query or sets the default value of the specified option s in style each key in kw is an option and each value is either a string or a sequence identifying the value for that option query or sets dynamic values of the specified option s in style each key in kw is an option and each value should be a list or a tuple usually containing statespecs grouped in tuples or list or something else of your preference a statespec is compound of one or more states and then a value returns the value specified for option in style if state is specified it is expected to be a sequence of one or more states if the default argument is set it is used as a fallback value in case no specification for option is found define the widget layout for given style if layoutspec is omitted return the layout specification for given style layoutspec is expected to be a list or an object different than none that evaluates to false if you want to turn off that style if it is a list or tuple or something else each item should be a tuple where the first item is the layout name and the second item should have the format described below layouts a layout can contain the value none if takes no options or a dict of options specifying how to arrange the element the layout mechanism uses a simplified version of the pack geometry manager given an initial cavity each element is allocated a parcel valid options values are side whichside specifies which side of the cavity to place the element one of top right bottom or left if omitted the element occupies the entire cavity sticky nswe specifies where the element is placed inside its allocated parcel children sublayout specifies a list of elements to place inside the element each element is a tuple or other sequence where the first item is the layout name and the other is a layout will disable the layout etc could be any other word but this may make sense when calling layout style later create a new element in the current theme of given etype returns the list of elements defined in the current theme return the list of elementname s options creates a new theme it is an error if themename already exists if parent is specified the new theme will inherit styles elements and layouts from the specified parent theme if settings are present they are expected to have the same syntax used for theme_settings temporarily sets the current theme to themename apply specified settings and then restore the previous theme each key in settings is a style and each value may contain the keys configure map layout and element create and they are expected to have the same format as specified by the methods configure map layout and element_create respectively returns a list of all known themes if themename is none returns the theme in use otherwise set the current theme to themename refreshes all widgets and emits a themechanged event starting on tk 8 6 checking this global is no longer needed since it allows doing self tk call self _name theme use using ttk settheme instead of ttk style theme use causes the variable currenttheme to be updated also ttk settheme calls ttk style theme use in order to change theme base class for tk themed widgets constructs a ttk widget with the parent master standard options class cursor takefocus style scrollable widget options xscrollcommand yscrollcommand label widget options text textvariable underline image compound width widget states active disabled focus pressed selected background readonly alternate invalid returns the name of the element at position x y or the empty string if the point does not lie within any element x and y are pixel coordinates relative to the widget test the widget s state if callback is not specified returns true if the widget state matches statespec and false otherwise if callback is specified then it will be invoked with args kw if the widget state matches statespec statespec is expected to be a sequence modify or inquire widget state widget state is returned if statespec is none otherwise it is set according to the statespec flags and then a new state spec is returned indicating which flags were changed statespec is expected to be a sequence ttk button widget displays a textual label and or image and evaluates a command when pressed construct a ttk button widget with the parent master standard options class compound cursor image state style takefocus text textvariable underline width widget specific options command default width invokes the command associated with the button ttk checkbutton widget which is either in on or off state construct a ttk checkbutton widget with the parent master standard options class compound cursor image state style takefocus text textvariable underline width widget specific options command offvalue onvalue variable toggles between the selected and deselected states and invokes the associated command if the widget is currently selected sets the option variable to the offvalue option and deselects the widget otherwise sets the option variable to the option onvalue returns the result of the associated command ttk entry widget displays a one line text string and allows that string to be edited by the user constructs a ttk entry widget with the parent master standard options class cursor style takefocus xscrollcommand widget specific options exportselection invalidcommand justify show state textvariable validate validatecommand width validation modes none key focus focusin focusout all return a tuple of x y width height which describes the bounding box of the character given by index returns the name of the element at position x y or the empty string if the coordinates are outside the window force revalidation independent of the conditions specified by the validate option returns false if validation fails true if it succeeds sets or clears the invalid state accordingly ttk combobox widget combines a text field with a pop down list of values construct a ttk combobox widget with the parent master standard options class cursor style takefocus widget specific options exportselection justify height postcommand state textvariable values width if newindex is supplied sets the combobox value to the element at position newindex in the list of values otherwise returns the index of the current value in the list of values or 1 if the current value does not appear in the list sets the value of the combobox to value ttk frame widget is a container used to group other widgets together construct a ttk frame with parent master standard options class cursor style takefocus widget specific options borderwidth relief padding width height ttk label widget displays a textual label and or image construct a ttk label with parent master standard options class compound cursor image style takefocus text textvariable underline width widget specific options anchor background font foreground justify padding relief text wraplength ttk labelframe widget is a container used to group other widgets together it has an optional label which may be a plain text string or another widget construct a ttk labelframe with parent master standard options class cursor style takefocus widget specific options labelanchor text underline padding labelwidget width height tkinter name compatibility ttk menubutton widget displays a textual label and or image and displays a menu when pressed construct a ttk menubutton with parent master standard options class compound cursor image state style takefocus text textvariable underline width widget specific options direction menu ttk notebook widget manages a collection of windows and displays a single one at a time each child window is associated with a tab which the user may select to change the currently displayed window construct a ttk notebook with parent master standard options class cursor style takefocus widget specific options height padding width tab options state sticky padding text image compound underline tab identifiers tab_id the tab_id argument found in several methods may take any of the following forms an integer between zero and the number of tabs the name of a child window a positional specification of the form x y which defines the tab the string current which identifies the currently selected tab the string end which returns the number of tabs only valid for method index adds a new tab to the notebook if window is currently managed by the notebook but hidden it is restored to its previous position removes the tab specified by tab_id unmaps and unmanages the associated window hides the tab specified by tab_id the tab will not be displayed but the associated window remains managed by the notebook and its configuration remembered hidden tabs may be restored with the add command returns the name of the tab element at position x y or the empty string if none returns the numeric index of the tab specified by tab_id or the total number of tabs if tab_id is the string end inserts a pane at the specified position pos is either the string end an integer index or the name of a managed child if child is already managed by the notebook moves it to the specified position selects the specified tab the associated child window will be displayed and the previously selected window if different is unmapped if tab_id is omitted returns the widget name of the currently selected pane query or modify the options of the specific tab_id if kw is not given returns a dict of the tab option values if option is specified returns the value of that option otherwise sets the options to the corresponding values returns a list of windows managed by the notebook enable keyboard traversal for a toplevel window containing this notebook this will extend the bindings for the toplevel window containing this notebook as follows control tab selects the tab following the currently selected one shift control tab selects the tab preceding the currently selected one alt k where k is the mnemonic underlined character of any tab will select that tab multiple notebooks in a single toplevel may be enabled for traversal including nested notebooks however notebook traversal only works properly if all panes are direct children of the notebook the only and good difference i see is about mnemonics which works after calling this method control tab and shift control tab always works here at least ttk panedwindow widget displays a number of subwindows stacked either vertically or horizontally construct a ttk panedwindow with parent master standard options class cursor style takefocus widget specific options orient width height pane options weight overrides pack forget inserts a pane at the specified positions pos is either the string end and integer index or the name of a child if child is already managed by the paned window moves it to the specified position query or modify the options of the specified pane pane is either an integer index or the name of a managed subwindow if kw is not given returns a dict of the pane option values if option is specified then the value for that option is returned otherwise sets the options to the corresponding values if newpos is specified sets the position of sash number index may adjust the positions of adjacent sashes to ensure that positions are monotonically increasing sash positions are further constrained to be between 0 and the total size of the widget returns the new position of sash number index tkinter name compatibility ttk progressbar widget shows the status of a long running operation they can operate in two modes determinate mode shows the amount completed relative to the total amount of work to be done and indeterminate mode provides an animated display to let the user know that something is happening construct a ttk progressbar with parent master standard options class cursor style takefocus widget specific options orient length mode maximum value variable phase begin autoincrement mode schedules a recurring timer event that calls method step every interval milliseconds interval defaults to 50 milliseconds 20 steps second if omitted increments the value option by amount amount defaults to 1 0 if omitted stop autoincrement mode cancels any recurring timer event initiated by start ttk radiobutton widgets are used in groups to show or change a set of mutually exclusive options construct a ttk radiobutton with parent master standard options class compound cursor image state style takefocus text textvariable underline width widget specific options command value variable sets the option variable to the option value selects the widget and invokes the associated command returns the result of the command or an empty string if no command is specified ttk scale widget is typically used to control the numeric value of a linked variable that varies uniformly over some range construct a ttk scale with parent master standard options class cursor style takefocus widget specific options command from length orient to value variable modify or query scale options setting a value for any of the from from_ or to options generates a rangechanged event get the current value of the value option or the value corresponding to the coordinates x y if they are specified x and y are pixel coordinates relative to the scale widget origin ttk scrollbar controls the viewport of a scrollable widget construct a ttk scrollbar with parent master standard options class cursor style takefocus widget specific options command orient ttk separator widget displays a horizontal or vertical separator bar construct a ttk separator with parent master standard options class cursor style takefocus widget specific options orient ttk sizegrip allows the user to resize the containing toplevel window by pressing and dragging the grip construct a ttk sizegrip with parent master standard options class cursor state style takefocus ttk spinbox is an entry with increment and decrement arrows it is commonly used for number entry or to select from a list of string values construct a ttk spinbox widget with the parent master standard options class cursor style takefocus validate validatecommand xscrollcommand invalidcommand widget specific options to from_ increment values wrap format command sets the value of the spinbox to value ttk treeview widget displays a hierarchical collection of items each item has a textual label an optional image and an optional list of data values the data values are displayed in successive columns after the tree label construct a ttk treeview with parent master standard options class cursor style takefocus xscrollcommand yscrollcommand widget specific options columns displaycolumns height padding selectmode show item options text image values open tags tag options foreground background font image returns the bounding box relative to the treeview widget s window of the specified item in the form x y width height if column is specified returns the bounding box of that cell if the item is not visible i e if it is a descendant of a closed item or is scrolled offscreen returns an empty string returns a tuple of children belonging to item if item is not specified returns root children replaces item s child with newchildren children present in item that are not present in newchildren are detached from tree no items in newchildren may be an ancestor of item query or modify the options for the specified column if kw is not given returns a dict of the column option values if option is specified then the value for that option is returned otherwise sets the options to the corresponding values delete all specified items and all their descendants the root item may not be deleted unlinks all of the specified items from the tree the items and all of their descendants are still present and may be reinserted at another point in the tree but will not be displayed the root item may not be detached returns true if the specified item is present in the tree false otherwise if item is specified sets the focus item to item otherwise returns the current focus item or if there is none query or modify the heading options for the specified column if kw is not given returns a dict of the heading option values if option is specified then the value for that option is returned otherwise sets the options to the corresponding values valid options values are text text the text to display in the column heading image image_name specifies an image to display to the right of the column heading anchor anchor specifies how the heading text should be aligned one of the standard tk anchor values command callback a callback to be invoked when the heading label is pressed to configure the tree column heading call this with column 0 callback not registered yet do it now returns a description of the specified component under the point given by x and y or the empty string if no such component is present at that position returns the item id of the item at position y returns the data column identifier of the cell at position x the tree column has id 0 returns one of heading tree heading area separator space between two columns headings tree the tree area cell a data cell availability tk 8 6 returns the element at position x y availability tk 8 6 returns the integer index of item within its parent s list of children creates a new item and return the item identifier of the newly created item parent is the item id of the parent item or the empty string to create a new top level item index is an integer or the value end specifying where in the list of parent s children to insert the new item if index is less than or equal to zero the new node is inserted at the beginning if index is greater than or equal to the current number of children it is inserted at the end if iid is specified it is used as the item identifier iid must not already exist in the tree otherwise a new unique identifier is generated query or modify the options for the specified item if no options are given a dict with options values for the item is returned if option is specified then the value for that option is returned otherwise sets the options to the corresponding values as given by kw moves item to position index in parent s list of children it is illegal to move an item under one of its descendants if index is less than or equal to zero item is moved to the beginning if greater than or equal to the number of children it is moved to the end if item was detached it is reattached a sensible method name for reattaching detached items returns the identifier of item s next sibling or if item is the last child of its parent returns the id of the parent of item or if item is at the top level of the hierarchy returns the identifier of item s previous sibling or if item is the first child of its parent ensure that item is visible sets all of item s ancestors open option to true and scrolls the widget if necessary so that item is within the visible portion of the tree returns the tuple of selected items the specified items becomes the new selection add all of the specified items to the selection remove all of the specified items from the selection toggle the selection state of each specified item query or set the value of given item with one argument return a dictionary of column value pairs for the specified item with two arguments return the current value of the specified column with three arguments set the value of given column in given item to the specified value bind a callback for the given event sequence to the tag tagname when an event is delivered to an item the callbacks for each of the item s tags option are called query or modify the options for the specified tagname if kw is not given returns a dict of the option settings for tagname if option is specified returns the value for that option for the specified tagname otherwise sets the options to the corresponding values for the given tagname if item is specified returns 1 or 0 depending on whether the specified item has the given tagname otherwise returns a list of all items which have the specified tag availability tk 8 6 extensions a ttk scale widget with a ttk label widget indicating its current value the ttk scale can be accessed through instance scale and ttk label can be accessed through instance label construct a horizontal labeledscale with parent master a variable to be associated with the ttk scale widget and its range if variable is not specified a tkinter intvar is created widget specific options compound top or bottom specifies how to display the label relative to the scale defaults to top position scale and label according to the compound option dummy required to make frame correct height update the label as scale or variable changes destroy this widget and possibly its associated variable adjust the label position according to the scale force scale redraw value outside range set value back to the last valid one return current scale value set new scale value themed optionmenu based after tkinter s optionmenu which allows the user to select a value from a menu construct a themed optionmenu widget with master as the parent the resource textvariable set to variable the initially selected value specified by the default parameter the menu values given by values and additional keywords widget specific options style stylename menubutton style direction above below left right or flush menubutton direction command callback a callback that will be invoked after selecting an item build a new menu of radiobuttons with values and optionally a default value destroy this widget and its associated variable
__version__ = "0.3.1"

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

__all__ = ["Button", "Checkbutton", "Combobox", "Entry", "Frame", "Label",
           "Labelframe", "LabelFrame", "Menubutton", "Notebook", "Panedwindow",
           "PanedWindow", "Progressbar", "Radiobutton", "Scale", "Scrollbar",
           "Separator", "Sizegrip", "Spinbox", "Style", "Treeview",
           
           "LabeledScale", "OptionMenu",
           
           "tclobjs_to_py", "setup_master"]

import tkinter
from tkinter import _flatten, _join, _stringify, _splitdict


def _format_optvalue(value, script=False):
    
    if script:
        
        
        value = _stringify(value)
    elif isinstance(value, (list, tuple)):
        value = _join(value)
    return value

def _format_optdict(optdict, script=False, ignore=None):
    

    opts = []
    for opt, value in optdict.items():
        if not ignore or opt not in ignore:
            opts.append("-%s" % opt)
            if value is not None:
                opts.append(_format_optvalue(value, script))

    return _flatten(opts)

def _mapdict_values(items):
    
    
    
    
    
    
    opt_val = []
    for *state, val in items:
        if len(state) == 1:
            
            
            state = state[0] or ''
        else:
            
            state = ' '.join(state) 
        opt_val.append(state)
        if val is not None:
            opt_val.append(val)
    return opt_val

def _format_mapdict(mapdict, script=False):
    

    opts = []
    for opt, value in mapdict.items():
        opts.extend(("-%s" % opt,
                     _format_optvalue(_mapdict_values(value), script)))

    return _flatten(opts)

def _format_elemcreate(etype, script=False, *args, **kw):
    
    specs = ()
    opts = ()
    if etype == "image": 
        
        iname = args[0]
        
        
        imagespec = (iname, *_mapdict_values(args[1:]))
        if script:
            specs = (imagespec,)
        else:
            specs = (_join(imagespec),)
        opts = _format_optdict(kw, script)

    if etype == "vsapi":
        
        
        
        
        if len(args) < 3:
            class_name, part_id = args
            statemap = (((), 1),)
        else:
            class_name, part_id, statemap = args
        specs = (class_name, part_id, tuple(_mapdict_values(statemap)))
        opts = _format_optdict(kw, script)

    elif etype == "from": 
        
        
        specs = (args[0],) 
        if len(args) > 1: 
            opts = (_format_optvalue(args[1], script),)

    if script:
        specs = _join(specs)
        opts = ' '.join(opts)
        return specs, opts
    else:
        return *specs, opts


def _format_layoutlist(layout, indent=0, indent_size=2):
    
    script = []

    for layout_elem in layout:
        elem, opts = layout_elem
        opts = opts or {}
        fopts = ' '.join(_format_optdict(opts, True, ("children",)))
        head = "%s%s%s" % (' ' * indent, elem, (" %s" % fopts) if fopts else '')

        if "children" in opts:
            script.append(head + " -children {")
            indent += indent_size
            newscript, indent = _format_layoutlist(opts['children'], indent,
                indent_size)
            script.append(newscript)
            indent -= indent_size
            script.append('%s}' % (' ' * indent))
        else:
            script.append(head)

    return '\n'.join(script), indent

def _script_from_settings(settings):
    
    script = []
    
    
    for name, opts in settings.items():
        
        if opts.get('configure'): 
            s = ' '.join(_format_optdict(opts['configure'], True))
            script.append("ttk::style configure %s %s;" % (name, s))

        if opts.get('map'): 
            s = ' '.join(_format_mapdict(opts['map'], True))
            script.append("ttk::style map %s %s;" % (name, s))

        if 'layout' in opts: 
            if not opts['layout']:
                s = 'null' 
            else:
                s, _ = _format_layoutlist(opts['layout'])
            script.append("ttk::style layout %s {\n%s\n}" % (name, s))

        if opts.get('element create'): 
            eopts = opts['element create']
            etype = eopts[0]

            
            argc = 1 
            while argc < len(eopts) and not hasattr(eopts[argc], 'items'):
                argc += 1

            elemargs = eopts[1:argc]
            elemkw = eopts[argc] if argc < len(eopts) and eopts[argc] else {}
            specs, eopts = _format_elemcreate(etype, True, *elemargs, **elemkw)

            script.append("ttk::style element create %s %s %s %s" % (
                name, etype, specs, eopts))

    return '\n'.join(script)

def _list_from_statespec(stuple):
    
    if isinstance(stuple, str):
        return stuple
    result = []
    it = iter(stuple)
    for state, val in zip(it, it):
        if hasattr(state, 'typename'):  
            state = str(state).split()
        elif isinstance(state, str):
            state = state.split()
        elif not isinstance(state, (tuple, list)):
            state = (state,)
        if hasattr(val, 'typename'):
            val = str(val)
        result.append((*state, val))

    return result

def _list_from_layouttuple(tk, ltuple):
    
    ltuple = tk.splitlist(ltuple)
    res = []

    indx = 0
    while indx < len(ltuple):
        name = ltuple[indx]
        opts = {}
        res.append((name, opts))
        indx += 1

        while indx < len(ltuple): 
            opt, val = ltuple[indx:indx + 2]
            if not opt.startswith('-'): 
                break

            opt = opt[1:] 
            indx += 2

            if opt == 'children':
                val = _list_from_layouttuple(tk, val)

            opts[opt] = val

    return res

def _val_or_dict(tk, options, *args):
    
    options = _format_optdict(options)
    res = tk.call(*(args + options))

    if len(options) % 2: 
        return res

    return _splitdict(tk, res, conv=_tclobj_to_py)

def _convert_stringval(value):
    
    value = str(value)
    try:
        value = int(value)
    except (ValueError, TypeError):
        pass

    return value

def _to_number(x):
    if isinstance(x, str):
        if '.' in x:
            x = float(x)
        else:
            x = int(x)
    return x

def _tclobj_to_py(val):
    
    if val and hasattr(val, '__len__') and not isinstance(val, str):
        if getattr(val[0], 'typename', None) == 'StateSpec':
            val = _list_from_statespec(val)
        else:
            val = list(map(_convert_stringval, val))

    elif hasattr(val, 'typename'): 
        val = _convert_stringval(val)

    return val

def tclobjs_to_py(adict):
    
    for opt, val in adict.items():
        adict[opt] = _tclobj_to_py(val)

    return adict

def setup_master(master=None):
    
    if master is None:
        master = tkinter._get_default_root()
    return master


class Style(object):
    

    _name = "ttk::style"

    def __init__(self, master=None):
        master = setup_master(master)
        self.master = master
        self.tk = self.master.tk


    def configure(self, style, query_opt=None, **kw):
        
        if query_opt is not None:
            kw[query_opt] = None
        result = _val_or_dict(self.tk, kw, self._name, "configure", style)
        if result or query_opt:
            return result


    def map(self, style, query_opt=None, **kw):
        
        if query_opt is not None:
            result = self.tk.call(self._name, "map", style, '-%s' % query_opt)
            return _list_from_statespec(self.tk.splitlist(result))

        result = self.tk.call(self._name, "map", style, *_format_mapdict(kw))
        return {k: _list_from_statespec(self.tk.splitlist(v))
                for k, v in _splitdict(self.tk, result).items()}


    def lookup(self, style, option, state=None, default=None):
        
        state = ' '.join(state) if state else ''

        return self.tk.call(self._name, "lookup", style, '-%s' % option,
            state, default)


    def layout(self, style, layoutspec=None):
        
        lspec = None
        if layoutspec:
            lspec = _format_layoutlist(layoutspec)[0]
        elif layoutspec is not None: 
            lspec = "null" 
                           

        return _list_from_layouttuple(self.tk,
            self.tk.call(self._name, "layout", style, lspec))


    def element_create(self, elementname, etype, *args, **kw):
        
        *specs, opts = _format_elemcreate(etype, False, *args, **kw)
        self.tk.call(self._name, "element", "create", elementname, etype,
            *specs, *opts)


    def element_names(self):
        
        return tuple(n.lstrip('-') for n in self.tk.splitlist(
            self.tk.call(self._name, "element", "names")))


    def element_options(self, elementname):
        
        return tuple(o.lstrip('-') for o in self.tk.splitlist(
            self.tk.call(self._name, "element", "options", elementname)))


    def theme_create(self, themename, parent=None, settings=None):
        
        script = _script_from_settings(settings) if settings else ''

        if parent:
            self.tk.call(self._name, "theme", "create", themename,
                "-parent", parent, "-settings", script)
        else:
            self.tk.call(self._name, "theme", "create", themename,
                "-settings", script)


    def theme_settings(self, themename, settings):
        
        script = _script_from_settings(settings)
        self.tk.call(self._name, "theme", "settings", themename, script)


    def theme_names(self):
        
        return self.tk.splitlist(self.tk.call(self._name, "theme", "names"))


    def theme_use(self, themename=None):
        
        if themename is None:
            
            
            return self.tk.eval("return $ttk::currentTheme")

        
        
        
        self.tk.call("ttk::setTheme", themename)


class Widget(tkinter.Widget):
    

    def __init__(self, master, widgetname, kw=None):
        
        master = setup_master(master)
        tkinter.Widget.__init__(self, master, widgetname, kw=kw)


    def identify(self, x, y):
        
        return self.tk.call(self._w, "identify", x, y)


    def instate(self, statespec, callback=None, *args, **kw):
        
        ret = self.tk.getboolean(
                self.tk.call(self._w, "instate", ' '.join(statespec)))
        if ret and callback is not None:
            return callback(*args, **kw)

        return ret


    def state(self, statespec=None):
        
        if statespec is not None:
            statespec = ' '.join(statespec)

        return self.tk.splitlist(str(self.tk.call(self._w, "state", statespec)))


class Button(Widget):
    

    def __init__(self, master=None, **kw):
        
        Widget.__init__(self, master, "ttk::button", kw)


    def invoke(self):
        
        return self.tk.call(self._w, "invoke")


class Checkbutton(Widget):
    

    def __init__(self, master=None, **kw):
        
        Widget.__init__(self, master, "ttk::checkbutton", kw)


    def invoke(self):
        
        return self.tk.call(self._w, "invoke")


class Entry(Widget, tkinter.Entry):
    

    def __init__(self, master=None, widget=None, **kw):
        
        Widget.__init__(self, master, widget or "ttk::entry", kw)


    def bbox(self, index):
        
        return self._getints(self.tk.call(self._w, "bbox", index))


    def identify(self, x, y):
        
        return self.tk.call(self._w, "identify", x, y)


    def validate(self):
        
        return self.tk.getboolean(self.tk.call(self._w, "validate"))


class Combobox(Entry):
    

    def __init__(self, master=None, **kw):
        
        Entry.__init__(self, master, "ttk::combobox", **kw)


    def current(self, newindex=None):
        
        if newindex is None:
            return self.tk.getint(self.tk.call(self._w, "current"))
        return self.tk.call(self._w, "current", newindex)


    def set(self, value):
        
        self.tk.call(self._w, "set", value)


class Frame(Widget):
    

    def __init__(self, master=None, **kw):
        
        Widget.__init__(self, master, "ttk::frame", kw)


class Label(Widget):
    

    def __init__(self, master=None, **kw):
        
        Widget.__init__(self, master, "ttk::label", kw)


class Labelframe(Widget):
    

    def __init__(self, master=None, **kw):
        
        Widget.__init__(self, master, "ttk::labelframe", kw)

LabelFrame = Labelframe 


class Menubutton(Widget):
    

    def __init__(self, master=None, **kw):
        
        Widget.__init__(self, master, "ttk::menubutton", kw)


class Notebook(Widget):
    

    def __init__(self, master=None, **kw):
        
        Widget.__init__(self, master, "ttk::notebook", kw)


    def add(self, child, **kw):
        
        self.tk.call(self._w, "add", child, *(_format_optdict(kw)))


    def forget(self, tab_id):
        
        self.tk.call(self._w, "forget", tab_id)


    def hide(self, tab_id):
        
        self.tk.call(self._w, "hide", tab_id)


    def identify(self, x, y):
        
        return self.tk.call(self._w, "identify", x, y)


    def index(self, tab_id):
        
        return self.tk.getint(self.tk.call(self._w, "index", tab_id))


    def insert(self, pos, child, **kw):
        
        self.tk.call(self._w, "insert", pos, child, *(_format_optdict(kw)))


    def select(self, tab_id=None):
        
        return self.tk.call(self._w, "select", tab_id)


    def tab(self, tab_id, option=None, **kw):
        
        if option is not None:
            kw[option] = None
        return _val_or_dict(self.tk, kw, self._w, "tab", tab_id)


    def tabs(self):
        
        return self.tk.splitlist(self.tk.call(self._w, "tabs") or ())


    def enable_traversal(self):
        
        
        
        
        self.tk.call("ttk::notebook::enableTraversal", self._w)


class Panedwindow(Widget, tkinter.PanedWindow):
    

    def __init__(self, master=None, **kw):
        
        Widget.__init__(self, master, "ttk::panedwindow", kw)


    forget = tkinter.PanedWindow.forget 


    def insert(self, pos, child, **kw):
        
        self.tk.call(self._w, "insert", pos, child, *(_format_optdict(kw)))


    def pane(self, pane, option=None, **kw):
        
        if option is not None:
            kw[option] = None
        return _val_or_dict(self.tk, kw, self._w, "pane", pane)


    def sashpos(self, index, newpos=None):
        
        return self.tk.getint(self.tk.call(self._w, "sashpos", index, newpos))

PanedWindow = Panedwindow 


class Progressbar(Widget):
    

    def __init__(self, master=None, **kw):
        
        Widget.__init__(self, master, "ttk::progressbar", kw)


    def start(self, interval=None):
        
        self.tk.call(self._w, "start", interval)


    def step(self, amount=None):
        
        self.tk.call(self._w, "step", amount)


    def stop(self):
        
        self.tk.call(self._w, "stop")


class Radiobutton(Widget):
    

    def __init__(self, master=None, **kw):
        
        Widget.__init__(self, master, "ttk::radiobutton", kw)


    def invoke(self):
        
        return self.tk.call(self._w, "invoke")


class Scale(Widget, tkinter.Scale):
    

    def __init__(self, master=None, **kw):
        
        Widget.__init__(self, master, "ttk::scale", kw)


    def configure(self, cnf=None, **kw):
        
        retval = Widget.configure(self, cnf, **kw)
        if not isinstance(cnf, (type(None), str)):
            kw.update(cnf)
        if any(['from' in kw, 'from_' in kw, 'to' in kw]):
            self.event_generate('<<RangeChanged>>')
        return retval


    def get(self, x=None, y=None):
        
        return self.tk.call(self._w, 'get', x, y)


class Scrollbar(Widget, tkinter.Scrollbar):
    

    def __init__(self, master=None, **kw):
        
        Widget.__init__(self, master, "ttk::scrollbar", kw)


class Separator(Widget):
    

    def __init__(self, master=None, **kw):
        
        Widget.__init__(self, master, "ttk::separator", kw)


class Sizegrip(Widget):
    

    def __init__(self, master=None, **kw):
        
        Widget.__init__(self, master, "ttk::sizegrip", kw)


class Spinbox(Entry):
    

    def __init__(self, master=None, **kw):
        
        Entry.__init__(self, master, "ttk::spinbox", **kw)


    def set(self, value):
        
        self.tk.call(self._w, "set", value)


class Treeview(Widget, tkinter.XView, tkinter.YView):
    

    def __init__(self, master=None, **kw):
        
        Widget.__init__(self, master, "ttk::treeview", kw)


    def bbox(self, item, column=None):
        
        return self._getints(self.tk.call(self._w, "bbox", item, column)) or ''


    def get_children(self, item=None):
        
        return self.tk.splitlist(
                self.tk.call(self._w, "children", item or '') or ())


    def set_children(self, item, *newchildren):
        
        self.tk.call(self._w, "children", item, newchildren)


    def column(self, column, option=None, **kw):
        
        if option is not None:
            kw[option] = None
        return _val_or_dict(self.tk, kw, self._w, "column", column)


    def delete(self, *items):
        
        self.tk.call(self._w, "delete", items)


    def detach(self, *items):
        
        self.tk.call(self._w, "detach", items)


    def exists(self, item):
        
        return self.tk.getboolean(self.tk.call(self._w, "exists", item))


    def focus(self, item=None):
        
        return self.tk.call(self._w, "focus", item)


    def heading(self, column, option=None, **kw):
        
        cmd = kw.get('command')
        if cmd and not isinstance(cmd, str):
            
            kw['command'] = self.master.register(cmd, self._substitute)

        if option is not None:
            kw[option] = None

        return _val_or_dict(self.tk, kw, self._w, 'heading', column)


    def identify(self, component, x, y):
        
        return self.tk.call(self._w, "identify", component, x, y)


    def identify_row(self, y):
        
        return self.identify("row", 0, y)


    def identify_column(self, x):
        
        return self.identify("column", x, 0)


    def identify_region(self, x, y):
        
        return self.identify("region", x, y)


    def identify_element(self, x, y):
        
        return self.identify("element", x, y)


    def index(self, item):
        
        return self.tk.getint(self.tk.call(self._w, "index", item))


    def insert(self, parent, index, iid=None, **kw):
        
        opts = _format_optdict(kw)
        if iid is not None:
            res = self.tk.call(self._w, "insert", parent, index,
                "-id", iid, *opts)
        else:
            res = self.tk.call(self._w, "insert", parent, index, *opts)

        return res


    def item(self, item, option=None, **kw):
        
        if option is not None:
            kw[option] = None
        return _val_or_dict(self.tk, kw, self._w, "item", item)


    def move(self, item, parent, index):
        
        self.tk.call(self._w, "move", item, parent, index)

    reattach = move 


    def next(self, item):
        
        return self.tk.call(self._w, "next", item)


    def parent(self, item):
        
        return self.tk.call(self._w, "parent", item)


    def prev(self, item):
        
        return self.tk.call(self._w, "prev", item)


    def see(self, item):
        
        self.tk.call(self._w, "see", item)


    def selection(self):
        
        return self.tk.splitlist(self.tk.call(self._w, "selection"))


    def _selection(self, selop, items):
        if len(items) == 1 and isinstance(items[0], (tuple, list)):
            items = items[0]

        self.tk.call(self._w, "selection", selop, items)


    def selection_set(self, *items):
        
        self._selection("set", items)


    def selection_add(self, *items):
        
        self._selection("add", items)


    def selection_remove(self, *items):
        
        self._selection("remove", items)


    def selection_toggle(self, *items):
        
        self._selection("toggle", items)


    def set(self, item, column=None, value=None):
        
        res = self.tk.call(self._w, "set", item, column, value)
        if column is None and value is None:
            return _splitdict(self.tk, res,
                              cut_minus=False, conv=_tclobj_to_py)
        else:
            return res


    def tag_bind(self, tagname, sequence=None, callback=None):
        
        self._bind((self._w, "tag", "bind", tagname), sequence, callback, add=0)


    def tag_configure(self, tagname, option=None, **kw):
        
        if option is not None:
            kw[option] = None
        return _val_or_dict(self.tk, kw, self._w, "tag", "configure",
            tagname)


    def tag_has(self, tagname, item=None):
        
        if item is None:
            return self.tk.splitlist(
                self.tk.call(self._w, "tag", "has", tagname))
        else:
            return self.tk.getboolean(
                self.tk.call(self._w, "tag", "has", tagname, item))




class LabeledScale(Frame):
    

    def __init__(self, master=None, variable=None, from_=0, to=10, **kw):
        
        self._label_top = kw.pop('compound', 'top') == 'top'

        Frame.__init__(self, master, **kw)
        self._variable = variable or tkinter.IntVar(master)
        self._variable.set(from_)
        self._last_valid = from_

        self.label = Label(self)
        self.scale = Scale(self, variable=self._variable, from_=from_, to=to)
        self.scale.bind('<<RangeChanged>>', self._adjust)

        
        scale_side = 'bottom' if self._label_top else 'top'
        label_side = 'top' if scale_side == 'bottom' else 'bottom'
        self.scale.pack(side=scale_side, fill='x')
        
        dummy = Label(self)
        dummy.pack(side=label_side)
        dummy.lower()
        self.label.place(anchor='n' if label_side == 'top' else 's')

        
        self.__tracecb = self._variable.trace_variable('w', self._adjust)
        self.bind('<Configure>', self._adjust)
        self.bind('<Map>', self._adjust)


    def destroy(self):
        
        try:
            self._variable.trace_vdelete('w', self.__tracecb)
        except AttributeError:
            pass
        else:
            del self._variable
        super().destroy()
        self.label = None
        self.scale = None


    def _adjust(self, *args):
        
        def adjust_label():
            self.update_idletasks() 

            x, y = self.scale.coords()
            if self._label_top:
                y = self.scale.winfo_y() - self.label.winfo_reqheight()
            else:
                y = self.scale.winfo_reqheight() + self.label.winfo_reqheight()

            self.label.place_configure(x=x, y=y)

        from_ = _to_number(self.scale['from'])
        to = _to_number(self.scale['to'])
        if to < from_:
            from_, to = to, from_
        newval = self._variable.get()
        if not from_ <= newval <= to:
            
            self.value = self._last_valid
            return

        self._last_valid = newval
        self.label['text'] = newval
        self.after_idle(adjust_label)

    @property
    def value(self):
        
        return self._variable.get()

    @value.setter
    def value(self, val):
        
        self._variable.set(val)


class OptionMenu(Menubutton):
    

    def __init__(self, master, variable, default=None, *values, **kwargs):
        
        kw = {'textvariable': variable, 'style': kwargs.pop('style', None),
              'direction': kwargs.pop('direction', None)}
        Menubutton.__init__(self, master, **kw)
        self['menu'] = tkinter.Menu(self, tearoff=False)

        self._variable = variable
        self._callback = kwargs.pop('command', None)
        if kwargs:
            raise tkinter.TclError('unknown option -%s' % (
                next(iter(kwargs.keys()))))

        self.set_menu(default, *values)


    def __getitem__(self, item):
        if item == 'menu':
            return self.nametowidget(Menubutton.__getitem__(self, item))

        return Menubutton.__getitem__(self, item)


    def set_menu(self, default=None, *values):
        
        menu = self['menu']
        menu.delete(0, 'end')
        for val in values:
            menu.add_radiobutton(label=val,
                command=(
                    None if self._callback is None
                    else lambda val=val: self._callback(val)
                ),
                variable=self._variable)

        if default:
            self._variable.set(default)


    def destroy(self):
        
        try:
            del self._variable
        except AttributeError:
            pass
        super().destroy()