Professional Documents
Culture Documents
Tkinter GUI Lesson2
Tkinter GUI Lesson2
com
TkinterGUIBasics
Example2:TkinterGUIWindow/AddingAButton
Thisisalittlemorethanjustaddingabutton.ThebuttonhasaFUNCTIONassignedtoitaquitcommand
toallowtheusertoexitcleanly.WhenmakingaGUIwewouldnormallyaimatmakingtheprogram'User
Friendly'andeasytouse.
AbuttonisknowninTkinterasa'Widget'
Addingabuttonmayseemaverysimplefeaturebutinthisexamplewehavelearntafewusefulthings:
Addcolourtothewriting
Addcolourtothebuttonbackground
Assignafontandfontsizetothetextwithinthebutton
Givethebuttonafunction(toquit)
Positionthebutton
OKsohereisthecode,itisthesameaslessononewith2extralines:(REMEMBERifyouarerunningany
versionofPython2youneedtochangetkintertoTkinterontheimportcommand)
from tkinter import *
top = Tk()
top.minsize(400,400)
top.title("Tkinter Basic GUI's")
exit_button = Button(top, text='Exit', fg='red', bg='black', font='freesansbold, 12', command=quit)
exit_button.pack(side=BOTTOM)
top.mainloop()
So,themajorityoftheabovecodeisthesame.TherearetwoadditionallineshereandIwillbrieflyexplain
them.Donotbeputoffbythesimplicityofaddingabutton,thereareafewusefullthingsinvolvedthatwill
helpyoulateron,especiallywhenaddingotherfeaturesliketextentryboxesandmenus.
SointhisexampleIadded2linesofcodetoputabuttoninthewindow.Hereisthefirstextralineofcode:
exit_button = Button(text='Exit', fg='red', bg='black', font='freesansbold, 12', command=quit)
YouwillfindthatPythonwon'tacceptitbecauseitalreadyknowsthenamequitassomethingelsea
commandtoquit.YoushouldusualybeabletospotthisbecauseifyoujusttypequitinaPythoneditwindow,
youwillnoticethecolourdifferencewhenPythonrecognisesit.Justtrytokeepitsimple.
Therestofthisadditionallineofcodeisallcontainedwithin()brackets.Hereiswhatisgoingon:
(top, text='Exit', fg='red', bg='black', font='freesansbold, 12', command=quit)
top:thistellsPythontoputthebuttoninthetopwindow(Root/Parentwindow)Ingeneralthisis
wheretheywillgounlesstoldotherwise(Ifyouhavesubwindowsforexample).
text='Exit':ThisassignsTexttothebuttoninourexamplewehavemadeanexitbuttonsothe
textshouldread'Exit'.
fg='red' :'fg'isanabbreviationfor'Foreground'.Inthiscaseitrepresentsthecolourofthetext.
bg='black':'bg'isanabbreviationof'Background'.Inthiscaseitrepresentsthecolourofthe
button.
font='freesansbold, 12':Fairlyselfexplanatory,wearesayingtoPythonthatwewantthe
texttobeaspecificfont,andsize.(***SEENOTEONFONTSBELOW***)
command=quit:ThistellsPythonthatwewantthebuttontodosomethingspecificbygivingita
command.WearemakinganExitbuttonsoluckilyPythonhasafunctionreadumadeforthis.Thequit
programcommandwillnowbeassignedtothisbutton.
Thesecondadditionallineis: exit_button.pack(side=BOTTOM)
Withouththisline,PythonwillnotaddthebuttonittotheGUI.Thereareafewwaystodothis.
pack()isknownasaLayoutManagerorGeometryManager
Packisthesimplestofthelayoutmanagers,andanotherpopularoneis'grid'andthethirdis'place'.Youcan
usegridtobemorespecificwithwhereyouwanttopositionthingswithinyourGUI.Iamstillgettingtogrips
withgrid()myselfsofornowIwilljustbeusingpack().AswearekeepingtheGUIbasicwedon'tneedtouse
grid.IfforexampleyouwantedtomakeacalculatorGUIwiththenumberslayedoutnicelylikebuttonsona
calculatoryouwouldNEEDtousethegridlayoutmanager.
Withthepack()featureyoucanincludesomebasicinstructionsforthepositionofyourwidget/button.You
canspecifytoplacethewidgetinanyofthefollowingpositions:
TOP/BOTTOM/LEFT/RIGHT
SinourcodewehavepositionedtheButtonatthebottomoftheGUIwith:
exit_button.pack(side=BOTTOM) 'bottom'canbereplacedwithanyoneofthepositionsnoted
above.Ifyoudon'taddapositionandjustusethepack()featurealonePythonwillnormallyplaceyourwidget
towardsthetopcenter.
HereisalistofavailableWidgetsinTkinter:
TheButtonWidget
TheCanvasWidget
TheCheckbuttonWidget
TheEntryWidget
TheFrameWidget
TheLabelWidget
TheLabelFrameWidget
TheListboxWidget
TheMenuWidget
TheMenubuttonWidget
TheMessageWidget
TheOptionMenuWidget
ThePanedWindowWidget
TheRadiobuttonWidget
TheScaleWidget
TheScrollbarWidget
TheSpinboxWidget
TheTextWidget
TheToplevelWidget
ThelistofWidgetswasfoundon:http://effbot.org/tkinterbook/tkinterindex.htmThereareanumberof
guidesandsourcesofdocumentationonline,forTkintergeneraluseIfoundthissitetobequiteuseful
***NOTEONFONTSFROMABOVE***
Youcanresearchtheexactlistofavailablefontsonline,andIwouldimagineyoucaninstallawiderrangeif
needed,BUT,IhaveasimplemethodIuse,toseethegenerallistofavailablefontsfromwithinPythonwithout
havingtolookonlineoranything:
Whileyou'reinPython,moveyou'remousepointertothetopbar(withfile,edit,format,run,options,windows
andhelpmenus)andclickonthemenuchoice'options'thenclickonthesubmenu'configureIDLE'andyou
willseealistofavailablefonts.DON'TUSETHISTOSELECTTHEFONTbecausethisisactuallyfor
changingthefontinwhichyoutypePythoncode.
YoucanusethislisttoseethefontsthatPythonhasreadilyavailableandchoosethenameofonetoadd
toyourGUIwidget.