12.07.2015 Views

Think Python - Denison University

Think Python - Denison University

Think Python - Denison University

SHOW MORE
SHOW LESS

You also want an ePaper? Increase the reach of your titles

YUMPU automatically turns print PDFs into web optimized ePapers that Google loves.

19.11. Exercises 193image = PIL.open('allen.png')photo2 = ImageTk.PhotoImage(image)g.la(image=photo2)1. Download image_demo.py, danger.gif and allen.png from thinkpython.com/code.Runimage_demo.py. YoumighthavetoinstallPILandImageTk. Theyareprobablyinyoursoftwarerepository, but ifnot you can get them frompythonware.com/products/pil/.2. In image_demo.py change the name of the second PhotoImage from photo2 to photo andrun theprogram again. You should see thesecond PhotoImage but not the first.TheproblemisthatwhenyoureassignphotoitoverwritesthereferencetothefirstPhotoImage,which then disappears. The same thing happens if you assign a PhotoImage to a localvariable; itdisappears when the function ends.To avoid this problem, you have to store a reference to each PhotoImage you want to keep.Youcanuseaglobalvariable,orstorePhotoImagesinadatastructureorasanattributeofanobject.Thisbehaviorcanbefrustrating,whichiswhyIamwarningyou(andwhytheexampleimagesays “Danger!”).3. Starting with this example, write a program that takes the name of a directory and loopsthrough all the files, displaying any files that PIL recognizes as images. You can use a trystatement tocatch the files PILdoesn’t recognize.When theuser clicks on theimage, the program should displaythe next one.4. PIL provides a variety of methods for manipulating images. You can read about them atpythonware.com/library/pil/handbook. As a challenge, choose a few of these methodsand provide a GUIfor applying them toimages.You can download asimplesolution fromthinkpython.com/code/ImageBrowser.py.Exercise 19.5 A vector graphics editor is a program that allows users to draw and edit shapes onthescreen and generate output files invector graphics formatslike Postscriptand SVG 1 .Write a simple vector graphics editor using Tkinter. At a minimum, it should allow users to drawlines, circles and rectangles, and it should use Canvas.dump to generate a Postscript description ofthecontents ofthe Canvas.As achallenge, you could allow users toselect and resizeitems on theCanvas.Exercise 19.6 Use Tkinter to write a basic web browser. It should have a Text widget where theuser can enter aURLand aCanvas todisplay the contents of thepage.You can use the urllib module to download files (see Exercise 14.5) and the HTMLParser moduletoparsethe HTML tags (seedocs.python.org/lib/module-HTMLParser.html).At a minimum your browser should handle plain text and hyperlinks. As a challenge you couldhandle background colors,text formattingtags and images.1 Seewikipedia.org/wiki/Vector_graphics_editor.

Hooray! Your file is uploaded and ready to be published.

Saved successfully!

Ooh no, something went wrong!