Example: bankruptcy

Tkinter 8.5reference:aGUIfor Python

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. quickreference5: generalinformationaboutthePythonlanguage . Foranexampleofa sizeableworkingapplication(around1000lin esofcode),seehuey: A colorandfont selectiontool6.

Tkinter8.5reference:aGUIfor Python John W. Shipman 2013-12-31 17:59 Abstract Describes the Tkinterwidget set for constructing graphical user interfaces (GUIs) in the Python programming language. Includes coverage of the ttk themed widgets. This publication is available in Web form

Tags:

  Python, Aguifor python, Aguifor

Information

Domain:

Source:

Link to this page:

Please notify us if you found a problem with this document:

Other abuse

Advertisement

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. quickreference5: generalinformationaboutthePythonlanguage . Foranexampleofa sizeableworkingapplication(around1000lin esofcode),seehuey: A colorandfont selectiontool6.

2 '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. 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?

3 Althoughtherearethreedifferent geometrymanagers inTkinter, () table agridworkofrowsandcolumns. Acellis theareaattheintersectionofonerowandoneco lumn. Thewidthofeachcolumnis thewidthofthewidestcellinthatcolumn. Theheightofeachrowis theheightofthelargestcellinthatrow. 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.

4 ,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. 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.

5 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?

6 '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.

7 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).Coordinatesthatyouspecifyasin tegersarealwaysexpressedinpixels,butanyc oordinatemaybespecifiedasa dimensionedquantity; , Dimensions ( ).

8 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'). Youcancreatea fontobject byimportingthetkFontmoduleandusingitsFon tclassconstructor:importtkFontfont= (option, ..)wheretheoptionsinclude:Thefontfamilyn ameasa fontnpixelshigh, 'bold'forboldface,'normal' 'italic'foritalic,'roman' , , ,togeta 36-pointboldHelveticaitalicface:helv36= (family='Helvetica',size=36,weight='bold ') If youarerunningundertheX WindowSystem,youcanuseanyoftheX ,thefontnamed'-*-lucidatypewriter-medium -r-*-*-*-140-*-*-*-*-*-*'isa listofallthefamiliesoffontsavailableonyo urplatform, ()Thereturnvalueis a.

9 Actual(option=None)If youpassnoarguments,yougetbacka dictionaryofthefont'sactualattributes, , (option) (option, ..)Usethismethodtochangeoneormoreoptions ona ,if youhaveaFontobjectcalledtitleFont, (family='times',size=18), ()Returnsa (text)Passthismethoda string,andit (option)If youcallthismethodwithnoarguments,it returnsa dictionaryofallthefont metrics. variable-widthfontand1fora AnchorsTheTkintermoduledefinesa ,anchorscanspecifywherea widgetis locatedinsidea framewhentheframeis ,wherenorthis upandwestis :Forexample,if youcreatea smallwidgetinsidea largeframeandusetheanchor= , youusedanchor= , , textanchor, (topleft) ,withtheleftedgeofthetextboxpassingthrou ghthatpoint, Relief stylesThereliefstyleofa a screenshotofa 5-pixelborder;thedefaultborderwidthis BitmapsForbitmapoptionsinwidgets,thesebi tmapsareguaranteedtobeavailable:7 ,theyare'error','gray75','gray50','gray2 5','gray12','hourglass','info','questhea d','question', and'warning'.

10 (Xbitmap) CursorsTherearequitea Valuesof ImagesTherearethreegeneralmethodsfordisp layinggraphicimagesinyourTkinterapplicat ion. Todisplaybitmap(two-color) , , TheBitmapImageclass ( ). ,.pgm, , , ThePhotoImageclass ( ). reference14 ThePythonImagingLibrary(PIL)supportsimag esina 'scompaniondocumentforPILdocumentation:P ythonImagingLibrary(PIL) , (file=f[, background=b][, foreground=c])wherefis ,foreground(1)bitsintheimagewillbedispla yedasblackpixels,andbackground(0) ,usetheoptionalbackground=boptiontosetth ebackgroundtocolorb, andtheoptionalforeground=coptiontosetthe foregroundtocolorc. Forcolorspecification, , Colors ( ).Thisconstructorreturnsa ,todisplayanimageasa label,useaLabelwidget(seeSection12, TheLabelwidget ( )) andsupplytheBitmapImageobjectasthevalueo ftheimageoption:logo= (' ',foreground='red')Label(image=logo).gri d() ,.pgm, , (file=f)wherefis standardwayofdescribingthesizeandlocatio nofa :'wxh x y'where: 'x'.


Related search queries