You are on page 1of 2

BenWoodfieldraserppsprograms@gmail.

comTkinterGUIBasics

Example3:TkinterGUIWindow/Buttons&Functions
Inexample2IshowedhowtoaddabuttonthatallowstheusertocleanlyexittheGUIprogram.Acommand
wasassignedtothebuttonsoithadapurposeandactuallydidsomething.
InthisexampleIwilldemonstratehowtoaddanotherbutton,withanewfunctionthatwillprintamessageto
theShellwindowwhenclickedbytheuser.
Here'sthecodeinfull:
from tkinter import *
top = Tk()
top.title('Tkinter GUI - Example 3')
top.minsize(800, 800)
top.configure(bg='orange')
lbl = Label(top, text='A Basic Window With 2 Buttons')
lbl.pack()
def hello_callback(): print ('Button Clicked')
btn = Button(top, text='Click Here', font='freesansbold, 14', command=hello_callback)
btn.pack()
exit_button = Button(top, text='Exit', fg='red', bg='black', font='freesansbold, 14', command=quit)
exit_button.pack(side=BOTTOM)
top.mainloop()

WhenyoutypethiscodeoutinPython3andrunityoushouldseeafewmaindifferences.
1.
2.
3.
4.

Thewindowsizeislarger(simplestuffyoucanmakethisanysizeyouwant)
Thebackgroundcolourisorange(top.configure)
Wehavealabelinsertedtothewindow(likeaheadingbutnotthesameasaTitle)
Theresanotherbuttonsaying'ClickMe'(ClickitandseewhathappensintheShellwindow)

Iwillrunthroughthecodequicklytotryandexplainwhatishappening.Althoughwehavecoveredmostofit
inthefirsttwoexamples.Wehavechangedafewvisualdetails,butthemostsubstancialadditionisthenew
Button.Thisexamplemakesafunctioncalled'hello_callback'andassignsittoournewbuttontomakeitprinta
message.

from tkinter import *

WehaveimportedsomeextrathingsfromTkinterbutwithoutcurrentimportcomand/scriptwehaveaccessto
thethingsweneed.Ifwewantedto,wecouldjustspecificallyimportthethingswewillbeusing,butasour
GUI'sgetmorecomplexwewillfindwehavetoimportnumerousthingswherewecanneatlydoitinone
line.

Ifweweretoimportthingsindividually,itwouldlooksomethinglikethis:

from tkinter import Label, Button, Tk

Nextwehaveourmainsetupcommandsforourroot(toplevel)window:

top = Tk()
top.title('Tkinter GUI - Example 3')
top.minsize(800, 800)
top.configure(bg='orange')

Thefirstthreearenothingnewtousaswewrotetheminexample2'.Thetitleisslightlydifferentbutyoucan
writeanythingyouwantinbetweenthequotemarks.Thelastline:[top.configure(bg='orange')]Sets
uptheconfigurationoftheroot/topwindow(Tk)andwehaveassignedabackgroundcolourorange.
Now,ifyouhaveusedPygameyoumayknowthatcolorsinPythonusuallyhaveanumericalvalue(R,G,B)
RedGreenandBluearetheprimarycolorsandtheamountofeach(whenthethreearemixed)determinesthe
endcolour.LuckilyTkinterhassomeprebuiltcoloursreadymadesoyoucantypeinmosttraditionalcolours
intheplaceof'orange'andchangeityourself.Youcanevenadd'light'tosome(lightBlueforexample)butI
donothaveacompletelistofavailablecolourstohand.
Next:

lbl = Label(top, text='A Basic Window With 2 Buttons')


lbl.pack()

Nothingtoofancyhere,weareaddinga'Label'whichisverysimilartoa'Header'inatextdocument,onlyyou
canchoosetopositionalabelanywhere.Tkinterwillbydefaultpackitatthetopcenterwhichisfineforour
example.Alabelcanbeusedtogiveaninstruction,orapieceofinformationtotheuser.
Nowwemoveontoournewbutton.Wehavewrittenourownfunctionforthisbutton,averybasiconeby
Python'sstandards,andalthoughitissimpleitisstillveryeffective.OurnewfunctiontellsPythontoprinta
messagetotheShell.WhenwemadetheExitbuttonweuseda'quit'commandassignedtothebuttontoexit
cleanly.
Thistimeourcommandwillbethenewfunction:

def hello_callback(): print ('Button Clicked')

btn = Button(top, text='Click Here', font='freesansbold, 14', command=hello_callback)


btn.pack()

ThefirstlinetellsPythonwewantto'define'afunctioncalled'hello_callback'.Thedefinitionistoprintthe
message'ButtonClicked'.PythonwillautomaticallyprintthingstotheShellunlesstoldotherwise.Lateronwe
willseehowtoprintfeedbacktoawidgetwithinourGUIwindowinstead.
Youcanchangetheprintedmessagetoanythingyouwant,themainthingisthatyouunderstandhowtoassign
functionstobuttons/widgets.
Therestofthecodeisthesameasbeforeexit_buttonandtop.mainloop()

You might also like