0% found this document useful (0 votes)
98 views

Tkinter GUI Lesson2

Lesson 2 - building upon the first lesson....as the lessons continue we add more things to the GUI and explain each line of code fully. I am unable to post the accompanying codes in .py format so you will have to copy and paste the document's code - or message me and I will email you the python files for each PDF

Uploaded by

Ben Woodfield
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
98 views

Tkinter GUI Lesson2

Lesson 2 - building upon the first lesson....as the lessons continue we add more things to the GUI and explain each line of code fully. I am unable to post the accompanying codes in .py format so you will have to copy and paste the document's code - or message me and I will email you the python files for each PDF

Uploaded by

Ben Woodfield
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 3

BenWoodfieldraserppsprograms@gmail.

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)

Sothefirstpartofthislineofcode exit_button = ButtonissimplysayingtoPythonthatwewant


toaddaButton,andwewishtocallitexit_button.Youcancallyourfeaturesanythingwithinreason
meaningthatifyousticktoletteredwords(strings)youshouldbeOK.Asageneralruledon'tusenumbers,
andifyouchoosetoassignanamewhichPythonalreadyknowsasafunctionyouwillgeterrorstoo.
ForExample:WearemakingaQuit/Exitbutton.So,ifyoucallthebuttonquitlikethisitwon'twork:
quit=Button()

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.

You might also like