12.07.2015 Views

Think Python - Denison University

Think Python - Denison University

Think Python - Denison University

SHOW MORE
SHOW LESS

Create successful ePaper yourself

Turn your PDF publications into a flip-book with our unique Google optimized e-Paper software.

19.8. Binding 18919.8 BindingAbindingisanassociationbetweenawidget,aneventandacallback: whenanevent(likeabuttonpress)happens on awidget, thecallback isinvoked.Many widgets have default bindings. For example, when you press a button, the default bindingchangesthereliefofthebuttontomakeitlookdepressed. Whenyoureleasethebutton,thebindingrestoresthe appearance of the button and invokes thecallback specified withthecommandoption.Youcanusethebindmethodtooverridethesedefaultbindingsortoaddnewones. Forexample,thiscodecreatesabindingforacanvas(youcandownloadthecodeinthissectionfromthinkpython.com/code/draggable_demo.py):ca.bind('', make_circle)The first argument is an event string; this event is triggered when the user presses the left mousebutton. Other mouse events includeButtonMotion,ButtonReleaseandDouble-Button.The second argument is an event handler. An event handler is a function or bound method, like acallback, but an important difference is that an event handler takes an Event object as a parameter.Here isanexample:def make_circle(event):pos = ca.canvas_coords([event.x, event.y])item = ca.circle(pos, 5, fill='red')The Event object contains information about the type of event and details like the coordinates ofthe mouse pointer. In this example the information we need is the location of the mouse click.These values are in “pixel coordinates,” which are defined by the underlying graphical system. Themethodcanvas_coordstranslatesthemto“Canvascoordinates,”whicharecompatiblewithCanvasmethods likecircle.For Entry widgets, it is common to bind the event, which is triggered when the userpresses the Returnor Enter key. For example, thefollowing code creates a Button and anEntry.bu = g.bu('Make text item:', make_text)en = g.en()en.bind('', make_text)make_text is called when the Button is pressed or when the user hits Return while typing in theEntry. To make thiswork, weneed afunctionthat canbecalled asacommand (withnoarguments)or as anevent handler (withan Event as anargument):def make_text(event=None):text = en.get()item = ca.text([0,0], text)make_textgets thecontents of the Entryand displays it asaText item inthe Canvas.It is also possible to create bindings for Canvas items. The following is a class definition forDraggable, which is a child class of Item that provides bindings that implement drag-and-dropcapability.class Draggable(Item):

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

Saved successfully!

Ooh no, something went wrong!