Tải bản đầy đủ (.pdf) (448 trang)

Tkinter GUI application development cookbook packt publishing (2018)

Bạn đang xem bản rút gọn của tài liệu. Xem và tải ngay bản đầy đủ của tài liệu tại đây (1004 KB, 448 trang )


TkinterGUIApplicationDevelopmentCookbook


ApracticalsolutiontoyourGUIdevelopmentproblemswith
PythonandTkinter








AlejandroRodasdePaz













BIRMINGHAM-MUMBAI



TkinterGUIApplication
DevelopmentCookbook
Copyright©2018PacktPublishing
Allrightsreserved.Nopartofthisbookmaybereproduced,storedinaretrievalsystem,ortransmittedinany
formorbyanymeans,withoutthepriorwrittenpermissionofthepublisher,exceptinthecaseofbrief
quotationsembeddedincriticalarticlesorreviews.
Everyefforthasbeenmadeinthepreparationofthisbooktoensuretheaccuracyoftheinformationpresented.
However,theinformationcontainedinthisbookissoldwithoutwarranty,eitherexpressorimplied.Neitherthe
author,norPacktPublishingoritsdealersanddistributors,willbeheldliableforanydamagescausedoralleged
tohavebeencauseddirectlyorindirectlybythisbook.
PacktPublishinghasendeavoredtoprovidetrademarkinformationaboutallofthecompaniesandproducts
mentionedinthisbookbytheappropriateuseofcapitals.However,PacktPublishingcannotguaranteethe
accuracyofthisinformation.
CommissioningEditor:AmarabhaBanerjee
AcquisitionEditor:ReshmaRaman
ContentDevelopmentEditor:JasonPereira
TechnicalEditor:PrajaktaMhatre
CopyEditor:DhanyaBaburaj
ProjectCoordinator:SheejalShah
Proofreader:SafisEditing
Indexer:RekhaNair
ProductionCoordinator:DeepikaNaik
Firstpublished:March2018
Productionreference:1270318
PublishedbyPacktPublishingLtd.
LiveryPlace
35LiveryStreet
Birmingham
B32PB,UK.
ISBN978-1-78862-230-1

www.packtpub.com


Idedicatemyworktomyaunt,Elena,andmycousins,JuliaandLaura.Thisbookwould
nothavebeenpossiblewithouttheirloveandsupport.


mapt.io

Maptisanonlinedigitallibrarythatgivesyoufullaccesstoover
5,000booksandvideos,aswellasindustryleadingtoolstohelp
youplanyourpersonaldevelopmentandadvanceyourcareer.For
moreinformation,pleasevisitourwebsite.


Whysubscribe?
Spendlesstimelearningandmoretimecodingwith
practicaleBooksandVideosfromover4,000industry
professionals
ImproveyourlearningwithSkillPlansbuiltespeciallyfor
you
GetafreeeBookorvideoeverymonth
Maptisfullysearchable
Copyandpaste,print,andbookmarkcontent


PacktPub.com
DidyouknowthatPacktofferseBookversionsofeverybook
published,withPDFandePubfilesavailable?Youcanupgradeto
theeBookversionatwww.PacktPub.comandasaprintbookcustomer,

youareentitledtoadiscountontheeBookcopy.Getintouchwith
usatformoredetails.
Atwww.PacktPub.com,youcanalsoreadacollectionoffreetechnical
articles,signupforarangeoffreenewsletters,andreceiveexclusive
discountsandoffersonPacktbooksandeBooks.


Contributors


Abouttheauthor
AlejandroRodasdePazisacomputerengineerfromSeville,
Spain.HehasdevelopedseveralprojectswithPython,fromweb
crawlerstoartificialintelligencealgorithms.Hehasalsoused
Tkinterforbuildinganapplicationforthelightingsystemofthecity
ofAlmere(Netherlands).
Priortothispublication,Alejandroco-wrotePackt'stitlePython
GameDevelopmentbyExample,andcollaboratedasatechnical
revieweronthebookTkinterGUIApplicationDevelopment
Hotshot.
IwouldliketothanktheexceptionalteamatPacktPublishingfortheirassistanceduring
thisjourney,andwordscannotexpressmygratitudetoJasonandPrajaktafortheir
understandingandimmensepatience.


Aboutthereviewers
JavierBecerraElcintoreceivedhisPhDinimageprocessing
fromtheUniversitédeBordeauxin2006.In2010hestarted
workingasaself-employeddeveloperworkingwithPythonand
C++,andin2014hecofoundedPanoimagenS.L.There,hehas

continuedtodevelopsoftwareforindustrialandprecision
agricultureapplications.Javierlecturesregularlyonscientific
programminginprivatecompaniesandseveralSpanishresearch
institutions.

MarcosPerezGonzalezworksinthetreatmentofmultimedia
documentdatabaseswithPython.Previously,hehadbeenusingit
asgluebetweenprojectsandtechnologiesformorethan10years.
Atthebeginningofhiscareer,heusedPythonforembedding
purposesandmultiplatformGUIprogramming.
HeisamemberofthePythonSpainassociationandthePython
Madridmeetup.Moreover,hehasbeenamemberoftheboardof
directorsoftheSpanishAssociationofComputerEngineering.
Heholdsamaster'sdegreeincomputerengineeringfromthe
UniversityofValladolid.

BrysonTyrrellisasystemsdevelopmentengineeratJamfin
Minneapolis,Minnesota.Inadditiontotheresponsibilitiesofhis
role,BrysonhasspokenatvariousITconferences(includingthe
JamfNationUserConference,PennStateMacAdmins,MacAdmins
andDevelopersUK,andAtlassianSummit)andmaintainsa


numberofopensourcetoolsfortheMacadmincommunityonhis
GitHubaccount.



Packtissearchingforauthors
likeyou

Ifyou'reinterestedinbecominganauthorforPackt,pleasevisitauth
ors.packtpub.comandapplytoday.Wehaveworkedwiththousandsof
developersandtechprofessionals,justlikeyou,tohelpthemshare
theirinsightwiththeglobaltechcommunity.Youcanmakea
generalapplication,applyforaspecifichottopicthatweare
recruitinganauthorfor,orsubmityourownidea.


Preface
Asoneofthemoreversatileprogramminglanguages,Pythoniswell
knownforitsbatteries-includedphilosophy,whichincludesarich
setofmodulesinitsstandardlibrary;Tkinteristhelibraryusedto
builddesktopapplications.BuiltovertheTkGUItoolkit,Tkinteris
acommonchoiceforrapidGUIdevelopment,andcomplex
applicationscanbenefitfromthefullcapabilitiesofthislibrary.
ThisbookcoversallofyourTkinterandPythonGUIdevelopment
problemsandsolutions.
TkinterGUIApplicationDevelopmentCookbookstartswithan
overviewofTkinterclassesandatthesametimeprovidesrecipes
forbasictopics,suchaslayoutpatternsandeventhandling.Next,
thisbookcovershowtodevelopcommonGUIpatterns,suchas
enteringandsavingdata,navigatingthroughmenusanddialogs,
andperforminglong-runningactionsinthebackground.Youcan
thenmakeyourappsleveragenetworkresourceseffectivelyand
performgraphicaloperationsonacanvasandrelatedtaskssuchas
detectingcollisionsbetweenitems.Finally,thisbookcoversusing
themedwidgets,anextensionofTkwidgetsthathaveamorenative
lookandfeel.
Bytheendofthebook,youwillhaveanin-depthknowledgeof
Tkinterclassesandknowhowtousethemtobuildefficientandrich

GUIapplications.


Whothisbookisfor
ThisbooktargetsPythondeveloperswhoarefamiliarwiththe
basicsofthelanguage—syntax,datastructures,andOOP—wantsto
learneffectivesolutionstothecommonchallengesofGUI
development,anddesirestodiscoverinterestingcapabilitiesthat
Tkintercanoffertobuildcomplexapplications.
YoudonotneedpreviousexperiencewithTkinterorotherGUI
developmentlibrariessincethefirstpartofthebookwillteachthe
basicsofthelibrarythroughtheintroductoryusecases.


Whatthisbookcovers
,GettingStartedwithTkinter,introducesthestructureofa
Tkinterprogramandshowsyouhowtoperformthemostcommon
tasks,suchascreatingwidgetsandhandlinguserevents.
Chapter1

,WindowLayout,demonstrateshowtoplacewidgetsusing
geometrymanagersandimprovethelayoutoflargeapplications.
Chapter2

,CustomizingWidgets,divesdeeperintoTkinter'swidget
configurationandappearancecustomization.
Chapter3

,DialogsandMenus,teachesyouhowtoimprovethe
navigationofTkinterappswithmenusanddialogs.

Chapter4

,Object-OrientedProgrammingandMVC,teachesyouhow
toeffectivelyapplydesignpatternsinyourTkinterapplications.
Chapter5

,AsynchronousProgramming,coversseveralrecipesto
executelong-runningactionswithoutfreezingtheapplication—a
recurringprobleminGUIdevelopment.
Chapter6

,CanvasandGraphics,explorestheCanvaswidgetandthe
typesofitemsyoucanaddtothecanvasandhowtomanipulate
them.
Chapter7

,ThemedWidgets,teachesyouhowtoextendTkinter
applicationswiththeTk-themedwidgetset.
Chapter8


Togetthemostoutofthis
book
Togetupandrunning,userswillneedtohavethefollowing
technologiesinstalled:
Python3.x
Anyoperatingsystem


Downloadtheexamplecode

files
Youcandownloadtheexamplecodefilesforthisbookfromyour
accountatwww.packtpub.com.Ifyoupurchasedthisbookelsewhere,you
canvisitwww.packtpub.com/supportandregistertohavethefilesemailed
directlytoyou.
Youcandownloadthecodefilesbyfollowingthesesteps:
1. Loginorregisteratwww.packtpub.com.
2. SelecttheSUPPORTtab.
3. ClickonCodeDownloads&Errata.
4. EnterthenameofthebookintheSearchboxandfollowthe
onscreeninstructions.
Oncethefileisdownloaded,pleasemakesurethatyouunzipor
extractthefolderusingthelatestversionof:
WinRAR/7-ZipforWindows
Zipeg/iZip/UnRarXforMac
7-Zip/PeaZipforLinux
ThecodebundleforthebookisalsohostedonGitHubathttps://githu
b.com/PacktPublishing/Tkinter-GUI-Application-Development-Cookbook.Incase
there'sanupdatetothecode,itwillbeupdatedontheexisting
GitHubrepository.


Wealsohaveothercodebundlesfromourrichcatalogofbooksand
videosavailableatCheckthemout!


Downloadthecolorimages
WealsoprovideaPDFfilethathascolorimagesofthe
screenshots/diagramsusedinthisbook.Youcandownloadithere:
/>

.

mentCookbook_ColorImages.pdf


Conventionsused
Thereareanumberoftextconventionsusedthroughoutthisbook.
:Indicatescodewordsintext,databasetablenames,folder
names,filenames,fileextensions,pathnames,dummyURLs,user
input,andTwitterhandles.Hereisanexample:
"Thedelete()methodtakestwoargumentsthatindicatetherangeof
thecharactersthatshouldbedeleted."
CodeInText

Ablockofcodeissetasfollows:
fromtkinterimport*

root=Tk()
btn=Button(root,text="Clickme!")
btn.config(command=lambda:print("Hello,Tkinter!"))
btn.pack(padx=120,pady=30)
root.title("MyTkinterapp")
root.mainloop()

Whenwewishtodrawyourattentiontoaparticularpartofacode
block,therelevantlinesoritemsaresetinbold:
defshow_caption(self,event):
caption=tk.Label(self,...)
caption.place(in_=event.widget,x=event.x,y=event.y)
#...


Bold:Indicatesanewterm,animportantword,orwordsthatyou
seeonscreen.Forexample,wordsinmenusordialogboxesappear
inthetextlikethis.Hereisanexample:"Thefirstwillbe
labeledChoosefile."


Warningsorimportantnotesappearlikethis.
Tipsandtricksappearlikethis.


Getintouch
Feedbackfromourreadersisalwayswelcome.
Generalfeedback:Emailandmentionthebook
titleinthesubjectofyourmessage.Ifyouhavequestionsaboutany
aspectofthisbook,pleaseemailusat
Errata:Althoughwehavetakeneverycaretoensuretheaccuracy
ofourcontent,mistakesdohappen.Ifyouhavefoundamistakein
thisbook,wewouldbegratefulifyouwouldreportthistous.Please
visitwww.packtpub.com/submit-errata,selectingyourbook,clickingonthe
ErrataSubmissionFormlink,andenteringthedetails.
Piracy:Ifyoucomeacrossanyillegalcopiesofourworksinany
formontheInternet,wewouldbegratefulifyouwouldprovideus
withthelocationaddressorwebsitename.Pleasecontactusat
withalinktothematerial.
Ifyouareinterestedinbecominganauthor:Ifthereisa
topicthatyouhaveexpertiseinandyouareinterestedineither
writingorcontributingtoabook,pleasevisitauthors.packtpub.com.



Reviews
Pleaseleaveareview.Onceyouhavereadandusedthisbook,why
notleaveareviewonthesitethatyoupurchaseditfrom?Potential
readerscanthenseeanduseyourunbiasedopiniontomake
purchasedecisions,weatPacktcanunderstandwhatyouthink
aboutourproducts,andourauthorscanseeyourfeedbackontheir
book.Thankyou!
FormoreinformationaboutPackt,pleasevisitpacktpub.com.


GettingStartedwithTkinter
Inthischapter,wewillcoverthefollowingrecipes:
StructuringaTkinterapplication
Workingwithbuttons
Creatingtextentries
Tracingtextchanges
Validatingatextentry
Selectingnumericalvalues
Creatingselectionswithradiobuttons
Implementingswitcheswithcheckboxes
Displayingalistofitems
Handlingmouseandkeyboardevents
Settingthemainwindow'sicon,title,andsize


×