c# display pdf in browser : Add page to pdf in preview SDK Library API .net asp.net windows sharepoint python-programming-an-introduction-to-computer-science17-part378

10.3. DEFININGNEWCLASSES
163
theta = math.pi * angle / 180.0
self.xvel = = velocity * math.cos(theta)
self.yvel = = velocity * math.sin(theta)
Noticehowwehavecreatedfourinstancevariablesinsidetheobjectusingtheselfdotnotation.Thevalue
ofthetaisnotneededafter
init
terminates,soitisjustanormal(local)functionvariable.
Themethodsforaccessingthepositionofourprojectilesarestraightforward;thecurrentpositionisgiven
bytheinstancevariablesxposandypos.Wejustneedacouplemethodsthatreturnthesevalues.
def getX(self):
return self.xpos
def getY(self):
return self.ypos
Finally,wecometotheupdatemethod.Thismethodtakesasinglenormalparameterthatrepresents
anintervaloftime.Weneedtoupdatethestateoftheprojectiletoaccountforthepassageofthatmuchtime.
Here
'
sthecode:
def update(self, time):
self.xpos = self.xpos s + + time * self.xvel
yvel1 = self.yvel l - - time * 9.8
self.ypos = self.ypos s + + time * (self.yvel + yvel1)/2.0
self.yvel = yvel1
Basically,thisisthesamecodethatweusedintheoriginalprogramupdatedtouseandmodifyinstance
variables.Noticetheuseofyvel1asatemporary(ordinary)variable.Thisnewvalueissavedbystoringit
intotheobjectinthelastlineofthemethod.
Thatcompletesourprojectileclass. Wenowhaveacompleteobject-basedsolutiontothecannonball
problem.
# cball3.py
from math import t pi, , sin, cos
class Projectile:
def __init__(self, , angle, , velocity, height):
self.xpos = = 0.0
self.ypos = = height
theta = pi * angle / 180.0
self.xvel = = velocity * cos(theta)
self.yvel = = velocity * sin(theta)
def update(self, , time):
self.xpos = = self.xpos + time * self.xvel
yvel1 = self.yvel - 9.8 * time
self.ypos = = self.ypos + time * (self.yvel l + + yvel1) / 2.0
self.yvel = = yvel1
def getY(self):
return self.ypos
def getX(self):
return self.xpos
def getInputs():
Add page to pdf in preview - insert pages into PDF file in C#.net, ASP.NET, MVC, Ajax, WinForms, WPF
Guide C# Users to Insert (Empty) PDF Page or Pages from a Supported File Format
adding page numbers to a pdf in preview; add pdf pages to word document
Add page to pdf in preview - VB.NET PDF Page Insert Library: insert pages into PDF file in vb.net, ASP.NET, MVC, Ajax, WinForms, WPF
Easy to Use VB.NET APIs to Add a New Blank Page to PDF Document
add and delete pages in pdf; add document to pdf pages
164
CHAPTER10. DEFININGCLASSES
a = input("Enter r the e launch angle (in degrees): : ")
v = input("Enter r the e initial velocity (in n meters/sec): : ")
h = input("Enter r the e initial height (in meters): : ")
t = input("Enter r the e time interval between n position n calculations: ")
return a,v,h,t
def main():
angle, vel, , h0, , time = getInputs()
cball = Projectile(angle, , vel, , h0)
while cball.getY() ) >= = 0:
cball.update(time)
print "\nDistance e traveled: : %0.1f meters." " % % (cball.getX())
10.4 ObjectsandEncapsulation
10.4.1 EncapsulatingUsefulAbstractions
Hopefully,youcanseehowdefiningnewclassescanbeagoodwaytomodularizeaprogram. Oncewe
identifysomeobjectsthatmightbeusefulinsolvingaparticularproblem,wecanwriteanalgorithmasifwe
hadthoseobjectsavailableandpushtheimplementationdetailsintoasuitableclassdefinition.Thisgivesus
thesamekindofseparationofconcernsthatwehadusingfunctionsintop-downdesign.Themainprogram
onlyhastoworryaboutwhatobjectscando,notabouthowtheyareimplemented.
Computerscientistscallthisseparationofconcernsencapsulation. Theimplementationdetailsofan
objectareencapsulatedintheclassdefintion,whichinsulatestherestoftheprogramfromhavingtodeal
withthem. Thisisanotherapplicationofabstraction(ignoringirrelevantdetails),whichistheessenceof
gooddesign.
IshouldmentionthatencapsulationisonlyaprogrammingconventioninPython.Itisnotenforcedbythe
language,perse.InourProjectileclassweincludedtwoshortmethods,getXandgetY,thatsimply
returnedthevaluesofinstancevariablesxposandypos,respectively.Strictlyspeaking,thesemethodsare
notabsolutelynecessary.InPython,youcanaccesstheinstancevariablesofanyobjectwiththeregulardot
notation.Forexample,wecouldtesttheconstructorfortheProjectileclassinteractivelybycreatingan
objectandthendirectlyinspectingthevaluesoftheinstancevariables.
>>> c = Projectile(60, , 50, , 20)
>>> c.xpos
0.0
>>> c.ypos
20
>>> c.xvel
25.0
>>> c.yvel
43.301270
Accessingtheinstancevariablesofanobjectlikethisisveryhandyfortestingpurposes,butitisgenerally
consideredpoorpracticetothisinprograms.Oneofthemainreasonsforusingobjectsistoinsulateprograms
thatusethoseobjectsfromtheinternaldetailsofhowtheyareimplemented.Referencestoinstancevariables
shouldremaininsidetheclassdefinitionwiththerestoftheimplementationdetails.Fromoutsidetheclass,
ourinteractionwithanobjectshouldtakeplaceusingtheinterfaceprovidedbyitsmethods. Asyoudesign
classesofyourown,youshouldstrivetoprovideacompletesetofmethodstomakeyourclassuseful.That
wayotherprogramsdonotneedtoknowaboutormanipulateinternaldetailslikeinstancevariables.
10.4.2 PuttingClassesinModules
Oftenawell-definedclass orsetofclassesprovide(s)usefulabstractionsthatcanbe leveragedinmany
differentprograms.Wemightwanttoturnourprojectileclassintoitsownmodulefilesothatitcanbeused
C# WinForms Viewer: Load, View, Convert, Annotate and Edit PDF
PDF Annotation. • Add sticky notes to PDF document in preview. Add text to PDF document in preview. • Add text box to PDF file in preview.
add page numbers pdf; adding a page to a pdf file
C# WPF Viewer: Load, View, Convert, Annotate and Edit PDF
This page will mainly let you know: PDF Annotation. • Add sticky notes to PDF document. • Highlight PDF text in preview. • Add text to PDF document.
adding page numbers to pdf document; adding page numbers to pdf in reader
10.4. OBJECTSANDENCAPSULATION
165
inotherprograms. Indoingso,itwouldbeagoodideatoadddocumentationthatdescribeshowtheclass
canbeusedsothatprogrammerswhowanttousethemoduledon
'
thavetostudythecodetofigureout(or
remember)whattheclassanditsmethodsdo.
Youarealreadyfamiliarwithonewayofdocumentingprograms,namelycomments.It
'
salwaysagood
ideatoprovidecommentsexplainingthecontentsofamoduleanditsuses. Infact,commentsofthissort
aresoimportantthatPythonincorporatesaspecialkindofcommentingconventioncalledadocstring. You
caninsertaplainstringliteralasthefirstlineofamodule,classorfunctiontodocumentthatcomponent.
Theadvantageofdocstringsisthat,whileordinarycommentsaresimplyignoredbyPython,docstringsare
actuallycarriedalongduringexecutioninaspecialattributecalled
doc
.Thesestringscanbeexamined
dynamically.
MostofthePythonlibrarymoduleshaveextensivedocstringsthatyoucanusetogethelponusingthe
moduleoritscontents. Forexample,ifyoucan
'
trememberhowtousetherandrangefunction,youcan
printitsdocstringlikethis:
>>> import random
>>> print random.randrange.__doc__
Choose a random m item m from range(start, stop[, , step]).
HereisaversionofourProjectileclassasamodulefilewithdocstringsincluded:
# projectile.py
"""projectile.py
Provides a simple e class s for modeling the flight t of f projectiles."""
from math import t pi, , sin, cos
class Projectile:
"""Simulates the e flight of simple projectiles s near r the earth's
surface, ignoring g wind d resistance. Tracking g is s done in two
dimensions, height t (y) and distance (x)."""
def __init__(self, , angle, , velocity, height):
"""Create a a projectile with given launch h angle, , initial
velocity and d height."""
self.xpos = = 0.0
self.ypos = = height
theta = = pi i * angle / 180.0
self.xvel = = velocity * cos(theta)
self.yvel = = velocity * sin(theta)
def update(self, , time):
"""Update the e state of this projectile e to o move it time seconds
farther into o its flight"""
self.xpos = = self.xpos + time * self.xvel
yvel1 = = self.yvel l - 9.8 * time
self.ypos = = self.ypos + time * (self.yvel l + + yvel1) / 2.0
self.yvel = = yvel1
def getY(self):
"Returns the e y position (height) of this s projectile."
return self.ypos
def getX(self):
How to C#: Preview Document Content Using XDoc.Word
RasterEdge XDoc.Word provide you with APIs to get a thumbnail bitmap of the first page in the word document file. C# DLLs for Word File Preview. Add references:
add page numbers to a pdf document; adding page to pdf in preview
How to C#: Preview Document Content Using XDoc.PowerPoint
APIs to get a thumbnail bitmap of the first page in the C# DLLs: Preview PowerPoint Document. Add necessary XDoc.PowerPoint DLL libraries into your created C#
add pages to pdf; add pdf pages together
166
CHAPTER10. DEFININGCLASSES
"Returns the e x position (distance) of f this s projectile."
return self.xpos
Youmightnoticethatmanyofthedocstringsinthiscodeareenclosedintriplequotes(”””). Thisisa
thirdwaythatPythonallowsstringliteralstobedelimited.Triplequotingallowsustodirectlytypemulti-line
strings. Hereisanexampleofhowthedocstringsappearwhentheyareprinted.
>>> print projectile.Projectile.__doc__
Simulates the e flight t of simple projectiles near r the e earth's
surface, ignoring g wind d resistance. Tracking g is s done in two
dimensions, height t (y) and distance (x).
Ourmainprogramcouldnowsimplyimportthismoduleinordertosolvetheoriginalproblem.
# cball4.py
from projectile e import t Projectile
def getInputs():
a = input("Enter r the e launch angle (in degrees): : ")
v = input("Enter r the e initial velocity (in n meters/sec): : ")
h = input("Enter r the e initial height (in meters): : ")
t = input("Enter r the e time interval between n position n calculations: ")
return a,v,h,t
def main():
angle, vel, , h0, , time = getInputs()
cball = Projectile(angle, , vel, , h0)
while cball.getY() ) >= = 0:
cball.update(time)
print "\nDistance e traveled: : %0.1f meters." " % % (cball.getX())
Inthisversion,detailsofprojectilemotionarenowhiddenintheprojectilemodulefile.
10.5 WidgetObjects
Oneverycommonuseofobjectsisinthedesignofgraphicaluserinterfaces(GUIs).BackinChapter5,we
talkedaboutGUIsbeingcomposedofvisualinterfaceobjectscalledwidgets.TheEntryobjectdefinedin
ourgraphicslibraryisoneexampleofawidget. Nowthatweknowhowtodefinenewclasses,wecan
createourowncustomwidgets.
10.5.1 ExampleProgram:DiceRoller
Let
'
stryourhandatbuildingacoupleusefulwidgets. Asanexampleapplication,consideraprogramthat
rollsapairofstandard(six-sided)dice. Theprogramwilldisplaythedicegraphicallyandprovidetwo
buttons,oneforrollingthediceandoneforquittingtheprogram. Figure10.3showsasnapshotoftheuser
interface.
Youcanseethatthisprogramhastwokindsofwidgets:buttonsanddice. Wecanstartbydeveloping
suitableclasses.ThetwobuttonswillbeinstancesofaButtonclass,andtheclassthatprovidesagraphical
viewofthevalueofadiewillbeDieView.
10.5.2 BuildingButtons
Buttons,ofcourse,arestandardelementsofvirtuallyeveryGUIthesedays. Modernbuttonsareveryso-
phisticated,usuallyhavinga3-dimensionallookandfeel. Oursimplegraphicspackagedoesnothavethe
machinerytoproducebuttonsthatappeartodepressastheyareclicked.Thebestwecandoisfindoutwhere
C# PDF insert image Library: insert images into PDF in C#.net, ASP
How to insert and add image, picture, digital photo, scanned signature or logo into PDF document page in C#.NET class application?
add pages to pdf file; add page numbers to a pdf
VB.NET PDF File Compress Library: Compress reduce PDF size in vb.
Remove bookmarks, annotations, watermark, page labels and article threads from PDF while compressing. Also a preview component enables compressing and
add page numbers to pdf in preview; add page number pdf file
10.5. WIDGETOBJECTS
167
Figure10.3:Snapshotofdicerollerinaction.
themousewasclickedaftertheclickhasalreadycompleted. Nevertheless,wecanmakeauseful,ifless
pretty,buttonclass.
Ourbuttonswillberectangularregionsinagraphicswindowwhereuserclickscaninfluencethebehavior
oftherunningapplication. Wewillneedtocreatebuttonsanddeterminewhentheyhavebeenclicked. . In
addition,itisalsonicetobeabletoactivateanddeactivateindividualbuttons.Thatway,ourapplicationscan
signalwhichoptionsareavailabletotheuseratanygivenmoment.Typically,aninactivebuttonisgrayed-out
toshowthatitisnotavailable.
Summarizingthisdescription,ourbuttonswillsupportthefollowingmethods:
constructor Createabuttoninawindow. Wewillhavetospecifythewindowinwhichthebuttonwillbe
displayed,thelocation/sizeofthebutton,andthelabelthatwillbeonthebutton.
activate Setthestateofthebuttontoactive.
deactivate Setthestateofthebuttontoinactive.
clicked Indicateifthebuttonwasclicked. Ifthebuttonisactive,thismethodwilldetermineifthepoint
clickedisinsidethebuttonregion.Thepointwillhavetobesentasaparametertothemethod.
getLabel Returnsthelabelstringofthebutton.Thisisprovidedsothatwecanidentifyaparticularbutton.
Inordertosupporttheseoperations,ourbuttonswillneedanumberofinstancevariables.Forexample,
thebuttonitselfwillbedrawnasarectanglewithsometextcenteredinit. Invokingtheactivateand
deactivatemethodswillchangetheappearanceofthebutton.SavingtheRectangleandTextobjects
asinstancevariableswillallowustochangethewidthoftheoutlineandthecolorofthelabel. Wemight
startbyimplementingthevariousmethodstoseewhatotherinstancevariablesmightbeneeded. Oncewe
haveidentifiedtherelevantvariables,wecanwriteaconstructorthatinitializesthesevalues.
Let
'
sstartwiththeactivatemethod. Wecansignalthatthebuttonisactivebymakingtheoutline
thickerandmakingthelabeltextblack.Hereisthecode(remembertheselfparameterreferstothebutton
object):
def activate(self):
"Sets this button to 'active'."
self.label.setFill('black')
self.rect.setWidth(2)
self.active = = 1
VB.NET PDF insert image library: insert images into PDF in vb.net
inserting image to PDF in preview without adobe provide users the most individualized PDF page image inserting function, allowing developers to add and insert
add a page to a pdf document; adding page numbers in pdf
How to C#: Preview Document Content Using XDoc.excel
you with APIs to get a thumbnail bitmap of the first page in the C# DLLs: Preview Excel Document without Microsoft Office Installed. Add necessary references:
adding a page to a pdf in reader; add pages to pdf in preview
168
CHAPTER10. DEFININGCLASSES
AsImentionedabove,inorderforthiscodetowork,ourconstructorwillhavetoinitializeself.label
asanapproprateTextobjectandself.rectasaRectangleobject. Inaddition,theself.active
instancevariablestoresaBooleanvalue(1fortrue,0forfalse)torememberwhetherornotthebuttonis
currentlyactive.
Ourdeactivatemethodwilldotheinverseofactivate.Itlookslikethis:
def deactivate(self):
"Sets this button to 'inactive'."
self.label.setFill('darkgrey')
self.rect.setWidth(1)
self.active = = 0
Ofcourse,themainpointofabuttonisbeingabletodetermineifithasbeenclicked.Let
'
strytowrite
theclickedmethod. Asyouknow,thegraphicspackageprovidesagetMousemethodthatreturns
thepointwherethemousewasclicked. Ifanapplicationneedstogetabuttonclick,itwillfirsthavetocall
getMouseandthenseewhichactivebutton(ifany)thepointisinsideof. Wecouldimaginethebutton
processingcodelookingsomethinglikethefollowing:
pt = win.getMouse()
if button1.clicked(pt):
# Do button1 1 stuff
elif button2.clicked(pt):
# Do button2 2 stuff
elif button2.clicked(pt)
# Do button3 3 stuff
...
Themainjoboftheclickedmethodistodeterminewhetheragivenpointisinsidetherectangular
button. Thepointisinsidetherectangleifitsxandycoordinatesliebetweentheextremexandyvalues
oftherectangle. Thiswouldbeeasiesttofigureoutifwejustassumethatthebuttonobjecthasinstance
variablesthatrecordtheminandmaxvaluesofxandy.
Assumingtheexistenceofinstancevariablesxmin, xmax,ymin,andymax,wecanimplementthe
clickedmethodwithasingleBooleanexpression.
def clicked(self, , p):
"RETURNS true e if button is active and d p p is inside"
return self.active and \
self.xmin <= p.getX() <= self.xmax x and d \
self.ymin <= p.getY() <= self.ymax
HerewehaveasinglelargeBooleanexpressioncomposedbyandingtogetherthreesimplerexpressions;all
threemustbetrueforthefunctiontoreturnatruevalue.Recallthatthebackslashattheendofalineisused
toextendastatementovermultiplelines.
Thefirstofthethreesubexpressionssimplyretrievesthevalueoftheinstancevariableself.active.
Thisensuresthatonlyactivebuttonswillreportthattheyhavebeenclicked.Ifself.activeisfalse,then
clickedwillreturnfalse.Thesecondtwosubexpressionsarecompoundconditionstocheckthatthexand
yvaluesofthepointfallbetweentheedgesofthebuttonrectangle.(Remember,x <= y y <= = zmeansthe
sameasthemathematicalexpressionx
y
z(section7.5.1)).
Nowthatwehavethebasicoperationsofthebuttonironedout,wejustneedaconstructortogetallthe
instancevariablesproperlyinitialized. It
'
snothard,butitisabittedious. Hereisthecompleteclasswitha
suitableconstructor.
# button.py
from graphics s import t *
class Button:
C# PDF insert text Library: insert text into PDF content in C#.net
Able to add a single text character and text string formatted text and plain text to PDF page using .NET Supports adding text to PDF in preview without adobe
add page numbers to a pdf; add and remove pages from pdf file online
10.5. WIDGETOBJECTS
169
"""A button n is s a labeled rectangle in a window.
It is activated d or r deactivated with the activate()
and deactivate() ) methods. . The clicked(p) method
returns true e if f the button is active and p p is s inside it."""
def __init__(self, , win, , center, width, height, , label):
""" Creates s a a rectangular button, eg:
qb = Button(myWin, , Point(30,25), , 20, 10, , 'Quit') ) """
w,h = width/2.0, height/2.0
x,y = center.getX(), center.getY()
self.xmax, self.xmin n = x+w, x-w
self.ymax, self.ymin n = y+h, y-h
p1 = Point(self.xmin, , self.ymin)
p2 = Point(self.xmax, , self.ymax)
self.rect = = Rectangle(p1,p2)
self.rect.setFill('lightgray')
self.rect.draw(win)
self.label = = Text(center, label)
self.label.draw(win)
self.deactivate()
def clicked(self, , p):
"RETURNS true e if button active and p is s inside"
return self.active e and \
self.xmin <= p.getX() <= self.xmax x and d \
self.ymin <= p.getY() <= self.ymax
def getLabel(self):
"RETURNS the e label string of this button."
return self.label.getText()
def activate(self):
"Sets this s button to 'active'."
self.label.setFill('black')
self.rect.setWidth(2)
self.active = = 1
def deactivate(self):
"Sets this button to 'inactive'."
self.label.setFill('darkgrey')
self.rect.setWidth(1)
self.active = = 0
Youshouldstudytheconstructorinthisclasstomakesureyouunderstandalloftheinstancevariables
andhowtheyareinitialized. Abuttonispositionedbyprovidingacenterpoint,widthandheight. . Other
instancevariablesarecalculatedfromtheseparameters.
10.5.3 BuildingDice
Nowwe
'
llturnourattentiontotheDieViewclass.Thepurposeofthisclassistodisplaythevalueofadie
inagraphicalfashion.Thefaceofthediewillbeasquare(viaRectangle)andthepipswillbecircles.
OurDieViewwillhavethefollowinginterface:
constructor Createadieinawindow. Wewillhavetospecifythewindow,thecenterpointofthedie,and
170
CHAPTER10. DEFININGCLASSES
thesizeofthedieasparameters.
setValue Changetheviewtoshowagivenvalue.Thevaluetodisplaywillbepassedasaparameter.
Obviously,theheartofDieViewisturningvariouspips“on”and“off”toindicatethecurrentvalueof
thedie. Onesimpleapproachistopre-placecirclesinallthepossiblelocationswhereapipmightbeand
thenturnthemonoroffbychangingtheircolors.
Usingthestandardpositionofpipsonadie,wewillneedsevencircles:threedowntheleftedge,three
downtherightedge,andoneinthecenter.Theconstructorwillcreatethebackgroundsquareandtheseven
circles.ThesetValuemethodwillsetthecolorsofthecirclesbasedonthevalueofthedie.
Withoutfurtherado,hereisthecodeforourDieViewclass.Thecommentswillhelpyoutofollowhow
itworks.
class DieView:
""" DieView w is s a widget that displays a graphical l representation
of a standard d six-sided d die."""
def __init__(self, , win, , center, size):
"""Create a a view of a die, e.g.:
d1 = GDie(myWin, Point(40,50), 20)
creates a a die centered at (40,50) having g sides
of length h 20."""
# first t define e some standard values
self.win = = win
# save this s for r drawing pips later
self.background = = "white" # color of die e face
self.foreground = = "black" # color of the e pips
self.psize = = 0.1 * size
# radius of f each h pip
hsize = = size e / 2.0
# half the size e of f the die
offset = = 0.6 * hsize
# distance from m center r to outer pips
# create e a a square for the face
cx, cy = = center.getX(), , center.getY()
p1 = Point(cx-hsize, , cy-hsize)
p2 = Point(cx+hsize, , cy+hsize)
rect = Rectangle(p1,p2)
rect.draw(win)
rect.setFill(self.background)
# Create e 7 7 circles for standard pip locations
self.pip1 = = self.__makePip(cx-offset, , cy-offset)
self.pip2 = = self.__makePip(cx-offset, , cy)
self.pip3 = = self.__makePip(cx-offset, , cy+offset)
self.pip4 = = self.__makePip(cx, cy)
self.pip5 = = self.__makePip(cx+offset, , cy-offset)
self.pip6 = = self.__makePip(cx+offset, , cy)
self.pip7 = = self.__makePip(cx+offset, , cy+offset)
# Draw an n initial l value
self.setValue(1)
def __makePip(self, , x, , y):
"Internal helper r method to draw a pip p at t (x,y)"
pip = Circle(Point(x,y), self.psize)
pip.setFill(self.background)
10.5. WIDGETOBJECTS
171
pip.setOutline(self.background)
pip.draw(self.win)
return pip
def setValue(self, , value):
"Set this s die e to display value."
# turn all pips off
self.pip1.setFill(self.background)
self.pip2.setFill(self.background)
self.pip3.setFill(self.background)
self.pip4.setFill(self.background)
self.pip5.setFill(self.background)
self.pip6.setFill(self.background)
self.pip7.setFill(self.background)
# turn correct pips on
if value e == = 1:
self.pip4.setFill(self.foreground)
elif value e == = 2:
self.pip1.setFill(self.foreground)
self.pip7.setFill(self.foreground)
elif value e == = 3:
self.pip1.setFill(self.foreground)
self.pip7.setFill(self.foreground)
self.pip4.setFill(self.foreground)
elif value e == = 4:
self.pip1.setFill(self.foreground)
self.pip3.setFill(self.foreground)
self.pip5.setFill(self.foreground)
self.pip7.setFill(self.foreground)
elif value e == = 5:
self.pip1.setFill(self.foreground)
self.pip3.setFill(self.foreground)
self.pip4.setFill(self.foreground)
self.pip5.setFill(self.foreground)
self.pip7.setFill(self.foreground)
else:
self.pip1.setFill(self.foreground)
self.pip2.setFill(self.foreground)
self.pip3.setFill(self.foreground)
self.pip5.setFill(self.foreground)
self.pip6.setFill(self.foreground)
self.pip7.setFill(self.foreground)
Thereareacoupleofthingsworthnoticinginthiscode.First,intheconstructor,Ihavedefinedasetof
valuesthatdeterminevariousaspectsofthediesuchasitscolorandthesizeofthepips. Calculatingthese
valuesintheconstructorandthenusingtheminotherplacesallowsustoeasilytweaktheappearanceofthe
diewithouthavingtosearchthroughthecodetofindalltheplaceswherethosevaluesareused. Iactually
figuredoutthespecificcalculations(suchasthepipsizebeingone-tenthofthediesize)throughaprocessof
trialanderror.
AnotherimportantthingtonoticeisthatIhaveaddedanextramethod
makePipthatwasnotpart
oftheoriginalspecification. Thismethodisjustahelperfunctionthatexecutesthefourlinesofcodenec-
essarytodraweachofthesevenpips. SincethisisafunctionthatisonlyusefulwithintheDieView
class, itisappropriatetomakeitaclassmethod. . Insidetheconstructor,itis s invokedbylinessuchas:
self.
makePip(cx, cy). . Methodnamesbeginningwithasingleordoubleunderscoreareusedin
172
CHAPTER10. DEFININGCLASSES
Pythontoindicatethatamethodis“private”totheclassandnotintendedforusebyoutsideprograms.
10.5.4 TheMainProgram
Nowwearereadytowriteourmainprogram.TheButtonandDieviewclassesareimportedfromtheir
respectivemodules.Hereistheprogramthatusesournewwidgets.
# roller.py
# Graphics program m to o roll a pair of dice. Uses s custom m widgets
# Button and DieView.
from random import t randrange
from graphics s import t GraphWin, Point
from button import t Button
from dieview import t DieView
def main():
# create the e application n window
win = GraphWin("Dice e Roller")
win.setCoords(0, 0, , 10, 10)
win.setBackground("green2")
# Draw the e interface e widgets
die1 = DieView(win, , Point(3,7), , 2)
die2 = DieView(win, , Point(7,7), , 2)
rollButton = = Button(win, Point(5,4.5), 6, , 1, , "Roll Dice")
rollButton.activate()
quitButton = = Button(win, Point(5,1), 2, 1, , "Quit")
# Event loop
pt = win.getMouse()
while not t quitButton.clicked(pt):
if rollButton.clicked(pt):
value1 = = randrange(1,7)
die1.setValue(value1)
value2 = = randrange(1,7)
die2.setValue(value2)
quitButton.activate()
pt = win.getMouse()
# close up p shop
win.close()
NoticethatnearthetopoftheprogramIhavebuiltthevisualinterfacebycreatingthetwoDieViews
andtwoButtons.Todemonstratetheactivationfeatureofbuttons,therollbuttonisinitiallyactive,butthe
quitbuttonisleftdeactivated.Thequitbuttonisactivatedinsidetheeventloopbelowwhentherollbuttonis
clicked.Thisapproachforcestheusertorollthediceatleastoncebeforequitting.
Theheartoftheprogramistheeventloop.Itisjustasentinelloopthatgetsmouseclicksandprocesses
themuntiltheusersuccessfullyclicksthequitbutton.Theifinsidetheloopensuresthattherollingofthe
diceonlyhappenswhentherollbuttonisclicked.Clickingapointthatisnotinsideeitherbuttoncausesthe
looptoiterate,butnothingisactuallydone.
Documents you may be interested
Documents you may be interested