Transcription of Tkinter 8.5reference:aGUIfor Python
1 Reference: a GUI forPythonJohn W. Shipman2013-12-3117:59 AbstractDescribestheTkinterwidgetsetforc onstructinggraphicaluserinterfaces(GUIs) availableinWebform1andalsoasa PDFdocument2. of () 221 (coption) : : :Structuringa 1681. A cross-platform graphicaluser interface builderfor PythonTkinteris a GUI(graphicaluserinterface) referenceNewMexicoTechComputerCenterPert inentreferences: FredrikLundh,whowroteTkinter, hastwoversionsofhisAn Introductionto Tkinter : a morecomplete1999version3anda 2005version4thatpresentsa fewnewerfeatures.
2 Quickreference5: generalinformationaboutthePythonlanguage . Foranexampleofa sizeableworkingapplication(around1000lin esofcode),seehuey: A colorandfont selectiontool6. 'llstartbylookingatthevisiblepartofTkint er: the frontpanel A minimalapplicationHereis a trivialTkinterprogramcontainingonlya Quitbutton:#!/usr/bin/envpython1importTk interas tk2classApplication( ):3def __init__(self,master=None) (self,master) () ()def createWidgets(self) (self,text='Quit',command= ) ()7app = Application() ('Sampleapplication') ()101 Thislinemakesthescriptself-executing, 'snamespace,butrenamesit ' , buttonlabeled Quit . Sampleapplication .10 Startstheapplication'smainloop, reference43.
3 DefinitionsBeforeweproceed,let' ,butingeneralit referstoa willbedecoratedwiththestandardframeandco ntrolsforyoursystem' ,althoughyourapplicationcanpreventthiswi dgetThegenerictermforanyofthebuildingblo cksthatmakeupanapplicationina :buttons,radiobuttons,textfields,frames, , ,parentWhenanywidgetis created,aparent-childrelationshipis ,if youplacea textlabelinsidea frame,theframeis Layout managementLaterwewilldiscussthewidgets, window?Althoughtherearethreedifferent geometrymanagers inTkinter, () table agridworkofrowsandcolumns. Acellis theareaattheintersectionofonerowandoneco lumn. Thewidthofeachcolumnis thewidthofthewidestcellinthatcolumn. Theheightofeachrowis theheightofthelargestcellinthatrow.
4 Forwidgetsthatdonotfilltheentirecell, ,orstretchthewidgettofitit,ineithertheho rizontalorverticaldimension. Youcancombinemultiplecellsintoonelargera rea,a widget,it doesnotappearuntilyouregisterit witha ,constructionandplacingofa widgetis a two- (parent, ..) (..)whereConstructoris oneofthewidgetclasseslikeButton,Frame, andsoon,andparentis () ()methodTodisplaya (option=value, ..)Thismethodregistersa widgetwwiththegridgeometrymanager ifyoudon'tdothis,thewidgetwillexistinter nally,butit ,seeTable1, ()geometrymanager ( ).Table1. Argumentsof ()geometrymanagerThecolumnnumberwhereyou wantthewidgetgridded, ,youcangrabmultiplecellsofa , (row=0,column=2,columnspan=3)wouldplacew idgetwina cellthatspanscolumns2, 3, and4 childofsomewidgetw2, usein_=w2.
5 ,countingfrom0. Thedefaultis column,however, , (row=3,column=2,rowspan=4,columnspan=5)w ouldplacewidgetwinanareaformedbymerging2 0cells,withrownumbers3 6andcolumnnumbers2 If youdonotprovideastickyattribute,thedefau ltbehavioris tocenterthewidgetinthecell. Youcanpositionthewidgetina cornerofthecellbyusingsticky= (topright), (bottomright), (bottomleft), (topleft). Youcanpositionthewidgetcenteredagainston esideofthecellbyusingsticky= (topcenter), (rightcenter), (bottomcenter), (leftcenter). Usesticky= + centeredhorizontally. Usesticky= + horizontallybutleaveit centeredvertically. Usesticky= + + + reference6 ,sticky= + + againstthewest(left) Othergrid managementmethodsThesegrid- (column=None,row=None,col2=None,row2=Non e)Returnsa 4-tupledescribingtheboundingboxofsomeora llofthegridsysteminwidgetw.
6 Thefirsttwonumbersreturnedarethexandycoo rdinatesoftheupperleftcornerofthearea, youpassincolumnandrowarguments, youalsopassincol2androw2arguments,theret urnedboundingboxdescribestheareaofthegri dfromcolumnscolumntocol2inclusive, , (0,0, 1, 1)returnstheboundingboxoffourcells, () stillexists,it justisn' ()it tomakeit appearagain,butit won' ()Returnsa dictionarywhosekeysarew's optionnames, (x,y)Givena coordinates(x,y)relativetothecontainingw idget,thismethodreturnsa tuple(col,row)describingwhatcellofw's ()Normally,allwidgetspropagatetheirdimen sions, ,sometimesyouwanttoforcea widgettobea certainsize, , (0)wherewis ()Thismethodis (), butitsgridoptionsareremembered,soif ()itagain,it ()Returnsa 2-tuplecontainingthenumberofcolumnsandth enumberofrows,respectively,inw' (row=None,column=None)Returnsa listofthewidgetsmanagedbywidgetw.
7 If noargumentsareprovided, ,orthecolumn= Configuringcolumnand row sizesUnlessyoutakecertainmeasures,thewid thofa gridcolumninsidea givenwidgetwillbeequaltothewidthofitswid estcell,andtheheightofa widgetcontrolsonlywhereit willbeplacedif it doesn' youwanttooverridethisautomaticsizingofco lumnsandrows, (N,option=value, ..)Inthegridlayoutinsidewidgetw, configurecolumnNsothatthegivenoptionhast hegivenvalue. Foroptions, (N,option=value, ..)Inthegridlayoutinsidewidgetw, , Columnand row configurationoptionsfor ()geometrymanagerThecolumnorrow' thereis nothinginthegivencolumnorrow,it willnotappear,evenif , columnorrowstretchable,usethisoptionands upplya ,ifweighta widgetwcontainsa gridlayout,theselineswilldistributethree -fourthsoftheextraspacetothefirstcolumna ndone- (0,weight=3) (1,weight=1)If thisoptionis notused, Makingthe root window resizeableDoyouwanttolettheuserresizeyou rentireapplicationwindow,anddistributeth eextraspaceamongitsinternalwidgets?
8 'snecessarytousethetechniquesforrowandco lumnsizemanagement, , Configuringcolumnandrowsizes ( ), tomakeyourApplicationwidget' ,thataloneis , Aminimalapplication ( ), yourunthisapplication,andresizethewindow ,thebuttonstaysthesamesize, ()methodintheminimalapplication. Inthisversion, createWidgets(self):top= () (0,weight=1) (0,weight=1) (0,weight=1) (0,weight=1) Button(self,text='Quit',command= ) (row=0,column=0,6sticky= + + + )1 The toplevelwindow is ,thiswindowis notyourApplicationwindow itis , ()methodonanywidgetinyourapplication;see Section26, Universalwidgetmethods ( ).2 Thislinemakesrow0 ofthetoplevelwindow' ofthetoplevelwindow' oftheApplicationwidget' oftheApplicationwidget' + + + ,changethesecondlineasshown:def __init__(self,master=None) (self,master) (sticky= + + + ) ()Theargumentsticky= + + + ()is necessarysothattheApplic-ationwidgetwill expandtofillitscellofthetop-levelwindow' Standard attributesBeforewelookatthewidgets,let's takea lookathowsomeoftheircommonattributes suchassizes,colorsandfonts arespecified.
9 Eachwidgethasa setofoptionsthataffectitsappearanceandbe havior attributessuchasfonts,colors,sizes,textl abels,andsuch. Youcanspecifyoptionswhencallingthewidget 'sconstructorusingkeywordargumentssuchas text='PANIC!'orheight=20. Afteryouhavecreateda widget,youcanlaterchangeanyoptionbyusing thewidget' () ' () , Universalwidgetmethods ( ) DimensionsVariouslengths,widths,andother dimensionsofwidgetscanbedescribedinmanyd ifferentunits. If youseta dimensiontoaninteger,it is assumedtobeinpixels. Youcanspecifyunitsbysettinga dimensiontoa stringcontaininga numberfollowedby:Table3. DimensionalunitsCentimeterscInchesiMilli metersmPrinter's points (about 1/72 ) The coordinate systemAsinmostcontemporarydisplaysystems ,theoriginofeachcoordinatesystemis atitsupperleftcorner,withthexcoordinatei ncreasingtowardtheright,andtheycoordinat eincreasingtowardthebottom:Thebaseunitis thepixel,withthetopleftpixelhavingcoordi nates(0,0).
10 Coordinatesthatyouspecifyasintegersareal waysexpressedinpixels,butanycoordinatema ybespecifiedasa dimensionedquantity; , Dimensions ( ). ColorsTherearetwogeneralwaystospecifycol orsinTkinter. Youcanusea stringspecifyingtheproportionofred,green ,andblueinhexadecimaldigits:Fourbitsperc olor#rgbEightbitspercolor#rrggbbTwelvebi tspercolor#rrrgggbbbForexample,'#fff'is white,'#000000'is black,'#000fff000'is puregreen,and'#00ffff'is purecyan(greenplusblue). 'white','black','red','green','blue','cy an','yellow', and'magenta' , Type fontsDependingonyourplatform,theremaybeu ptothreewaystospecifytypestyle. Asa tuplewhosefirstelementis thefontfamily,followedbya size(inpointsif positive,inpixelsifnegative),optionallyf ollowedbya stringcontainingoneormoreofthestylemodif iersbold,italic,underline, :('Helvetica','16')fora 16-pointHelveticaregular;('Times','24',' bolditalic')fora 20-pixelTimesboldfont,use('Times',-20,'b old').