Tkinterisnotathinwrapper,butaddsafairamountofitsownlogictomaketheexperiencemorepythonic.Thisdocumentationwillconcentrateontheseadditionsandchanges,andrefertotheofficialTcl/Tkdocumentationfordetailsthatareunchanged.
Note
Tcl/Tk8.5(2007)introducedamodernsetofthemeduserinterfacecomponentsalongwithanewAPItousethem.BotholdandnewAPIsarestillavailable.MostdocumentationyouwillfindonlinestillusestheoldAPIandcanbewoefullyoutdated.
Seealso
Tcl/TkResources:
Books:
Tcl/Tkisnotasinglelibrarybutratherconsistsofafewdistinctmodules,eachwithseparatefunctionalityanditsownofficialdocumentation.Python’sbinaryreleasesalsoshipanadd-onmoduletogetherwithit.
Internally,TkandTtkusefacilitiesoftheunderlyingoperatingsystem,i.e.,XlibonUnix/X11,CocoaonmacOS,GDIonWindows.
Whengiven(asastring),setstheDISPLAYenvironmentvariable.(X11only)
Nameoftheprofilefile.Bydefault,baseNameisderivedfromtheprogramname(sys.argv[0]).
Nameofthewidgetclass.UsedasaprofilefileandalsoasthenamewithwhichTclisinvoked(argv0ininterp).
IfTrue,executeallXservercommandssynchronously,sothaterrorsarereportedimmediately.Canbeusedfordebugging.(X11only)
Specifiestheidofthewindowinwhichtoembedtheapplication,insteadofitbeingcreatedasanindependenttoplevelwindow.idmustbespecifiedinthesamewayasthevalueforthe-useoptionfortoplevelwidgets(thatis,ithasaformlikethatreturnedbywinfo_id()).
NotethatonsomeplatformsthiswillonlyworkcorrectlyifidreferstoaTkframeortoplevelthathasits-containeroptionenabled.
ThemodulesthatprovideTksupportinclude:
MainTkintermodule.
Dialogtolettheuserchooseacolor.
Baseclassforthedialogsdefinedintheothermoduleslistedhere.
Commondialogstoallowtheusertospecifyafiletoopenorsave.
Utilitiestohelpworkwithfonts.
AccesstostandardTkdialogboxes.
Textwidgetwithaverticalscrollbarbuiltin.
Basicdialogsandconveniencefunctions.
Additionalmodules:
TurtlegraphicsinaTkwindow.
ThissectionisnotdesignedtobeanexhaustivetutorialoneitherTkorTkinter.Forthat,refertooneoftheexternalresourcesnotedearlier.Instead,thissectionprovidesaveryquickorientationtowhataTkinterapplicationlookslike,identifiesfoundationalTkconcepts,andexplainshowtheTkinterwrapperisstructured.
Theremainderofthissectionwillhelpyoutoidentifytheclasses,methods,andoptionsyou’llneedinyourTkinterapplication,andwheretofindmoredetaileddocumentationonthem,includingintheofficialTcl/Tkreferencemanual.
We’llstartbywalkingthrougha“HelloWorld”applicationinTkinter.Thisisn’tthesmallestonewecouldwrite,buthasenoughtoillustratesomekeyconceptsyou’llneedtoknow.
fromtkinterimport*fromtkinterimportttkroot=Tk()frm=ttk.Frame(root,padding=10)frm.grid()ttk.Label(frm,text="HelloWorld!").grid(column=0,row=0)ttk.Button(frm,text="Quit",command=root.destroy).grid(column=1,row=0)root.mainloop()Aftertheimports,thenextlinecreatesaninstanceoftheTkclass,whichinitializesTkandcreatesitsassociatedTclinterpreter.Italsocreatesatoplevelwindow,knownastherootwindow,whichservesasthemainwindowoftheapplication.
Thefollowinglinecreatesaframewidget,whichinthiscasewillcontainalabelandabuttonwe’llcreatenext.Theframeisfitinsidetherootwindow.
Thenextlinecreatesalabelwidgetholdingastatictextstring.Thegrid()methodisusedtospecifytherelativelayout(position)ofthelabelwithinitscontainingframewidget,similartohowtablesinHTMLwork.
Abuttonwidgetisthencreated,andplacedtotherightofthelabel.Whenpressed,itwillcallthedestroy()methodoftherootwindow.
Finally,themainloop()methodputseverythingonthedisplay,andrespondstouserinputuntiltheprogramterminates.
EventhissimpleprogramillustratesthefollowingkeyTkconcepts:
ATkinteruserinterfaceismadeupofindividualwidgets.EachwidgetisrepresentedasaPythonobject,instantiatedfromclasseslikettk.Frame,ttk.Label,andttk.Button.
Widgetsarearrangedinahierarchy.Thelabelandbuttonwerecontainedwithinaframe,whichinturnwascontainedwithintherootwindow.Whencreatingeachchildwidget,itsparentwidgetispassedasthefirstargumenttothewidgetconstructor.
Widgetshaveconfigurationoptions,whichmodifytheirappearanceandbehavior,suchasthetexttodisplayinalabelorbutton.Differentclassesofwidgetswillhavedifferentsetsofoptions.
Widgetsaren’tautomaticallyaddedtotheuserinterfacewhentheyarecreated.Ageometrymanagerlikegridcontrolswhereintheuserinterfacetheyareplaced.
Tkinterreactstouserinput,changesfromyourprogram,andevenrefreshesthedisplayonlywhenactivelyrunninganeventloop.Ifyourprogramisn’trunningtheeventloop,youruserinterfacewon’tupdate.
WhenyourapplicationusesTkinter’sclassesandmethods,internallyTkinterisassemblingstringsrepresentingTcl/Tkcommands,andexecutingthosecommandsintheTclinterpreterattachedtoyourapplication’sTkinstance.
Whetherit’stryingtonavigatereferencedocumentation,tryingtofindtherightmethodoroption,adaptingsomeexistingcode,ordebuggingyourTkinterapplication,therearetimesthatitwillbeusefultounderstandwhatthoseunderlyingTcl/Tkcommandslooklike.
Toillustrate,hereistheTcl/TkequivalentofthemainpartoftheTkinterscriptabove.
ttk::frame.frm-padding10grid.frmgrid[ttk::label.frm.lbl-text"HelloWorld!"]-column0-row0grid[ttk::button.frm.btn-text"Quit"-command"destroy."]-column1-row0Tcl’ssyntaxissimilartomanyshelllanguages,wherethefirstwordisthecommandtobeexecuted,withargumentstothatcommandfollowingit,separatedbyspaces.Withoutgettingintotoomanydetails,noticethefollowing:
Ifyou’renotsurehowtodosomethinginTkinter,andyoucan’timmediatelyfinditinthetutorialorreferencedocumentationyou’reusing,thereareafewstrategiesthatcanbehelpful.
First,rememberthatthedetailsofhowindividualwidgetsworkmayvaryacrossdifferentversionsofbothTkinterandTcl/Tk.Ifyou’researchingdocumentation,makesureitcorrespondstothePythonandTcl/Tkversionsinstalledonyoursystem.
Tofindoutwhatconfigurationoptionsareavailableonanywidget,callitsconfigure()method,whichreturnsadictionarycontainingavarietyofinformationabouteachobject,includingitsdefaultandcurrentvalues.Usekeys()togetjustthenamesofeachoption.
btn=ttk.Button(frm,...)print(btn.configure().keys())Asmostwidgetshavemanyconfigurationoptionsincommon,itcanbeusefultofindoutwhicharespecifictoaparticularwidgetclass.Comparingthelistofoptionstothatofasimplerwidget,likeaframe,isonewaytodothat.
WhilealloperationsinTkinterareimplementedasmethodcallsonwidgetobjects,you’veseenthatmanyTcl/Tkoperationsappearascommandsthattakeawidgetpathnameasitsfirstparameter,followedbyoptionalparameters,e.g.
destroy.grid.frm.btn-column0-row0Others,however,lookmorelikemethodscalledonawidgetobject(infact,whenyoucreateawidgetinTcl/Tk,itcreatesaTclcommandwiththenameofthewidgetpathname,withthefirstparametertothatcommandbeingthenameofamethodtocall).
Somewhatconfusingly,therearealsomethodsonallTkinterwidgetsthatdon’tactuallyoperateonthewidget,butoperateataglobalscope,independentofanywidget.Examplesaremethodsforaccessingtheclipboardorthesystembell.(TheyhappentobeimplementedasmethodsinthebaseWidgetclassthatallTkinterwidgetsinheritfrom).
APythoninterpretermayhavemanythreadsassociatedwithit.InTcl,multiplethreadscanbecreated,buteachthreadhasaseparateTclinterpreterinstanceassociatedwithit.Threadscanalsocreatemorethanoneinterpreterinstance,thougheachinterpreterinstancecanbeusedonlybytheonethreadthatcreatedit.
Tcl/Tkapplicationsarenormallyevent-driven,meaningthatafterinitialization,theinterpreterrunsaneventloop(i.e.Tk.mainloop())andrespondstoevents.Becauseitissingle-threaded,eventhandlersmustrespondquickly,otherwisetheywillblockothereventsfrombeingprocessed.Toavoidthis,anylong-runningcomputationsshouldnotruninaneventhandler,butareeitherbrokenintosmallerpiecesusingtimers,orruninanotherthread.ThisisdifferentfrommanyGUItoolkitswheretheGUIrunsinacompletelyseparatethreadfromallapplicationcodeincludingeventhandlers.
Anumberofspecialcasesexist:
Optionscontrolthingslikethecolorandborderwidthofawidget.Optionscanbesetinthreeways:
fred=Button(self,fg="red",bg="blue")Afterobjectcreation,treatingtheoptionnamelikeadictionaryindexfred["fg"]="red"fred["bg"]="blue"Usetheconfig()methodtoupdatemultipleattrssubsequenttoobjectcreationfred.config(fg="red",bg="blue")Foracompleteexplanationofagivenoptionanditsbehavior,seetheTkmanpagesforthewidgetinquestion.
Nodistinctionbetweenstandardandwidget-specificoptionsismadeinthisdocument.Someoptionsdon’tapplytosomekindsofwidgets.Whetheragivenwidgetrespondstoaparticularoptiondependsontheclassofthewidget;buttonshaveacommandoption,labelsdonot.
Theoptionssupportedbyagivenwidgetarelistedinthatwidget’smanpage,orcanbequeriedatruntimebycallingtheconfig()methodwithoutarguments,orbycallingthekeys()methodonthatwidget.Thereturnvalueofthesecallsisadictionarywhosekeyisthenameoftheoptionasastring(forexample,'relief')andwhosevaluesare5-tuples.
Someoptions,likebgaresynonymsforcommonoptionswithlongnames(bgisshorthandfor“background”).Passingtheconfig()methodthenameofashorthandoptionwillreturna2-tuple,not5-tuple.The2-tuplepassedbackwillcontainthenameofthesynonymandthe“real”option(suchas('bg','background')).
Index
Meaning
Example
0
optionname
'relief'
1
optionnamefordatabaselookup
2
optionclassfordatabaselookup
'Relief'
3
defaultvalue
'raised'
4
currentvalue
'groove'
Example:
ThepackerisoneofTk’sgeometry-managementmechanisms.Geometrymanagersareusedtospecifytherelativepositioningofwidgetswithintheircontainer-theirmutualmaster.Incontrasttothemorecumbersomeplacer(whichisusedlesscommonly,andwedonotcoverhere),thepackertakesqualitativerelationshipspecification-above,totheleftof,filling,etc-andworkseverythingouttodeterminetheexactplacementcoordinatesforyou.
Thesizeofanymasterwidgetisdeterminedbythesizeofthe“slavewidgets”inside.Thepackerisusedtocontrolwhereslavewidgetsappearinsidethemasterintowhichtheyarepacked.Youcanpackwidgetsintoframes,andframesintootherframes,inordertoachievethekindoflayoutyoudesire.Additionally,thearrangementisdynamicallyadjustedtoaccommodateincrementalchangestotheconfiguration,onceitispacked.
Notethatwidgetsdonotappearuntiltheyhavehadtheirgeometryspecifiedwithageometrymanager.It’sacommonearlymistaketoleaveoutthegeometryspecification,andthenbesurprisedwhenthewidgetiscreatedbutnothingappears.Awidgetwillappearonlyafterithashad,forexample,thepacker’spack()methodappliedtoit.
Thepack()methodcanbecalledwithkeyword-option/valuepairsthatcontrolwherethewidgetistoappearwithinitscontainer,andhowitistobehavewhenthemainapplicationwindowisresized.Herearesomeexamples:
Anchortype.Denoteswherethepackeristoplaceeachslaveinitsparcel.
Boolean,0or1.
Legalvalues:'x','y','both','none'.
Adistance-designatinginternalpaddingoneachsideoftheslavewidget.
Adistance-designatingexternalpaddingoneachsideoftheslavewidget.
Legalvaluesare:'left','right','top','bottom'.
Thecurrent-valuesettingofsomewidgets(liketextentrywidgets)canbeconnecteddirectlytoapplicationvariablesbyusingspecialoptions.Theseoptionsarevariable,textvariable,onvalue,offvalue,andvalue.Thisconnectionworksbothways:ifthevariablechangesforanyreason,thewidgetit’sconnectedtowillbeupdatedtoreflectthenewvalue.
TherearemanyusefulsubclassesofVariablealreadydefined:StringVar,IntVar,DoubleVar,andBooleanVar.Toreadthecurrentvalueofsuchavariable,calltheget()methodonit,andtochangeitsvalueyoucalltheset()method.Ifyoufollowthisprotocol,thewidgetwillalwaystrackthevalueofthevariable,withnofurtherinterventiononyourpart.
Forexample:
Togetatthetoplevelwindowthatcontainsagivenwidget,youcanoftenjustrefertothewidget’smaster.Ofcourseifthewidgethasbeenpackedinsideofaframe,themasterwon’trepresentatoplevelwindow.Togetatthetoplevelwindowthatcontainsanarbitrarywidget,youcancallthe_root()method.Thismethodbeginswithanunderscoretodenotethefactthatthisfunctionispartoftheimplementation,andnotaninterfacetoTkfunctionality.
Herearesomeexamplesoftypicalusage:
Youcanpassintegers0or1orthestrings"yes"or"no".
ThisisanyPythonfunctionthattakesnoarguments.Forexample:
defprint_it():print("hithere")fred["command"]=print_itcolorColorscanbegivenasthenamesofXcolorsinthergb.txtfile,orasstringsrepresentingRGBvaluesin4bit:"#RGB",8bit:"#RRGGBB",12bit:"#RRRGGGBBB",or16bit:"#RRRRGGGGBBBB"ranges,whereR,G,Bhererepresentanylegalhexdigit.Seepage160ofOusterhout’sbookfordetails.
ThestandardXcursornamesfromcursorfont.hcanbeused,withouttheXC_prefix.Forexampletogetahandcursor(XC_hand2),usethestring"hand2".Youcanalsospecifyabitmapandmaskfileofyourown.Seepage179ofOusterhout’sbook.
Screendistancescanbespecifiedineitherpixelsorabsolutedistances.Pixelsaregivenasnumbersandabsolutedistancesasstrings,withthetrailingcharacterdenotingunits:cforcentimetres,iforinches,mformillimetres,pforprinter’spoints.Forexample,3.5inchesisexpressedas"3.5i".
Tkusesalistfontnameformat,suchas{courier10bold}.Fontsizeswithpositivenumbersaremeasuredinpoints;sizeswithnegativenumbersaremeasuredinpixels.
Thisisastringoftheformwidthxheight,wherewidthandheightaremeasuredinpixelsformostwidgets(incharactersforwidgetsdisplayingtext).Forexample:fred["geometry"]="200x100".
Legalvaluesarethestrings:"left","center","right",and"fill".
Thisisastringwithfourspace-delimitedelements,eachofwhichisalegaldistance(seeabove).Forexample:"2345"and"3i2i4.5i2i"and"3c2c4c10.43c"arealllegalregions.
Determineswhattheborderstyleofawidgetwillbe.Legalvaluesare:"raised","sunken","flat","groove",and"ridge".
Thisisalmostalwaystheset()methodofsomescrollbarwidget,butcanbeanywidgetmethodthattakesasingleargument.
Mustbeoneof:"none","char",or"word".
Thebindmethodfromthewidgetcommandallowsyoutowatchforcertaineventsandtohaveacallbackfunctiontriggerwhenthateventtypeoccurs.Theformofthebindmethodis:
isaPythonfunction,takingoneargument,tobeinvokedwhentheeventoccurs.AnEventinstancewillbepassedastheargument.(Functionsdeployedthiswayarecommonlyknownascallbacks.)
isoptional,either''or'+'.Passinganemptystringdenotesthatthisbindingistoreplaceanyotherbindingsthatthiseventisassociatedwith.Passinga'+'meansthatthisfunctionistobeaddedtothelistoffunctionsboundtothiseventtype.
defturn_red(self,event):event.widget["activeforeground"]="red"self.button.bind("
Tk
TkinterEventField
%f
focus
%A
char
%h
height
%E
send_event
%k
keycode
%K
keysym
%s
state
%N
keysym_num
%t
time
%T
type
%w
width
%W
widget
%x
x
%X
x_root
%y
y
%Y
y_root
Anumberofwidgetsrequire“index”parameterstobepassed.TheseareusedtopointataspecificplaceinaTextwidget,ortoparticularcharactersinanEntrywidget,ortoparticularmenuitemsinaMenuwidget.
TheindexnotationforTextwidgetsisveryrichandisbestdescribedintheTkmanpages.
Someoptionsandmethodsformenusmanipulatespecificmenuentries.Anytimeamenuindexisneededforanoptionoraparameter,youmaypassin:
Imagesofdifferentformatscanbecreatedthroughthecorrespondingsubclassoftkinter.Image:
Eithertypeofimageiscreatedthrougheitherthefileorthedataoption(otheroptionsareavailableaswell).
Changedinversion3.13:AddedthePhotoImagemethodcopy_replace()tocopyaregionfromoneimagetootherimage,possiblywithpixelzoomingand/orsubsampling.Addfrom_coordsparametertoPhotoImagemethodscopy(),zoom()andsubsample().AddzoomandsubsampleparameterstoPhotoImagemethodcopy().
Theimageobjectcanthenbeusedwhereveranimageoptionissupportedbysomewidget(e.g.labels,buttons,menus).Inthesecases,Tkwillnotkeepareferencetotheimage.WhenthelastPythonreferencetotheimageobjectisdeleted,theimagedataisdeletedaswell,andTkwilldisplayanemptyboxwherevertheimagewasused.
TkallowsyoutoregisterandunregisteracallbackfunctionwhichwillbecalledfromtheTkmainloopwhenI/Oispossibleonafiledescriptor.Onlyonehandlermayberegisteredperfiledescriptor.Examplecode:
importtkinterwidget=tkinter.Tk()mask=tkinter.READABLE|tkinter.WRITABLEwidget.tk.createfilehandler(file,mask,callback)...widget.tk.deletefilehandler(file)