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.3. Canvas widgets 183Exercise 19.1 Write a program that creates a GUI with a single button. When the button is presseditshouldcreateasecondbutton. Whenthatbuttonispressed,itshouldcreatealabelthatsays,“Nicejob!”.What happens if you press the buttons more than once? You can see my solution at thinkpython.com/code/button_demo.py19.3 Canvas widgetsOne of the most versatile widgets is the Canvas, which creates a region for drawing lines, circlesand other shapes. Ifyou didExercise 15.4 you arealready familiarwithcanvases.The methodcacreates anew Canvas:canvas = g.ca(width=500, height=500)widthandheightarethedimensions of the canvas inpixels.After you create a widget, you can still change the values of the options with the config method.For example, thebgoption changes thebackground color:canvas.config(bg='white')The value of bg is a string that names a color. The set of legal color names is different for differentimplementations of <strong>Python</strong>, but all implementations provide at least:white blackred green bluecyan yellow magentaShapes on a Canvas are called items. For example, the Canvas method circle draws (you guessedit)acircle:item = canvas.circle([0,0], 100, fill='red')Thefirstargumentisacoordinatepairthatspecifiesthecenterofthecircle;thesecondistheradius.Gui.py provides a standard Cartesian coordinate system with the origin at the center of the Canvasand the positive y axis pointing up. This is different from some other graphics systems where theoriginisinthe upper leftcorner, withthe yaxis pointing down.Thefilloption specifies that the circleshould be filledinwithred.ThereturnvaluefromcircleisanItemobjectthatprovidesmethodsformodifyingtheitemonthecanvas. For example, you can useconfigtochange any of thecircle’s options:item.config(fill='yellow', outline='orange', width=10)widthis thethickness of theoutline inpixels;outlineisthecolor.Exercise 19.2 Write a program that creates a Canvas and a Button. When the user presses theButton, itshould draw acircleon thecanvas.

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

Saved successfully!

Ooh no, something went wrong!