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.

182 Chapter 19. Casestudy: TkinterEntry: A region where userscan typetext.Scrollbar: A widget that controls the visiblepart ofanother widget.Frame: A container, often invisible,that contains other widgets.The empty gray square you see when you create a Gui is a Frame. When you create a new widget,itisadded tothis Frame.19.2 Buttonsand callbacksThe methodbucreates aButton widget:button = g.bu(text='Press me.')The return value from bu is a Button object. The button that appears in the Frame is a graphicalrepresentation ofthis object; you can control thebutton by invoking methods onit.bu takes up to 32 parameters that control the appearance and function of the button. These parametersare called options. Instead of providing values for all 32 options, you can use keywordarguments, like text='Press me.', to specify only the options you need and use the default valuesfor therest.WhenyouaddawidgettotheFrame,itgets“shrink-wrapped;”thatis,theFrameshrinkstothesizeof theButton. Ifyou add morewidgets, the Frame grows toaccommodate them.The methodlacreates aLabel widget:label = g.la(text='Press the button.')By default, Tkinter stacks the widgets top-to-bottom and centers them. We’ll see how to overridethat behavior soon.If you press the button, you will see that it doesn’t do much. That’s because you haven’t “wired itup;” that is,you haven’t tolditwhat todo!The option that controls the behavior of a button is command. The value of command is a functionthat gets executed when the button is pressed. For example, here is a function that creates a newLabel:def make_label():g.la(text='Thank you.')Now wecan create abutton withthisfunction as itscommand:button2 = g.bu(text='No, press me!', command=make_label)When you press thisbutton, itshould executemake_labeland anew label should appear.The value of the command option is a function object, which is known as a callback because afteryoucallbutocreatethebutton,theflowofexecution“callsback”whentheuserpressesthebutton.This kind of flow is characteristic of event-driven programming. User actions, like button pressesandkeystrokes,arecalledevents. Inevent-drivenprogramming,theflowofexecutionisdeterminedby user actions rather than by theprogrammer.The challenge of event-driven programming is to construct a set of widgets and callbacks that workcorrectly (orat least generate appropriate errormessages) forany sequence of user actions.

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

Saved successfully!

Ooh no, something went wrong!