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.

188 Chapter 19. Casestudy: Tkinterdef run_text(self):source = self.te_code.get(1.0, END)self.inter.run_code(source, '')Unfortunately, the details of widget layout are different in other languages, and in different <strong>Python</strong>modules. Tkinter alone provides three different mechanisms for arranging widgets. These mechanismsarecalledgeometrymanagers.TheoneIdemonstratedinthissectionisthe“grid”geometrymanager; theothers are called “pack” and “place”.Fortunately, most of theconcepts inthissection apply toother GUI modules and other languages.19.7 Menusand CallablesA Menubutton is a widget that looks like a button, but when pressed it pops up a menu. After theuser selects anitem, themenu disappears.Here is code that creates a color selection Menubutton (you can download it from thinkpython.com/code/menubutton_demo.py):g = Gui()g.la('Select a color:')colors = ['red', 'green', 'blue']mb = g.mb(text=colors[0])mb creates the Menubutton. Initially, the text on the button is the name of the default color. Thefollowing loop creates one menu item foreach color:for color in colors:g.mi(mb, text=color, command=Callable(set_color, color))The firstargument ofmiistheMenubutton theseitems areassociated with.The command option is a Callable object, which is something new. So far we have seen functionsand bound methods used as callbacks, which works fine if you don’t have to pass any argumentsto the function. Otherwise you have to construct a Callable object that contains a function, likeset_color,and itsarguments, likecolor.The Callable object stores a reference to the function and the arguments as attributes. Later, whentheuser clicks onamenu item,the callback calls thefunction and passes thestoredarguments.Here iswhatset_colormight look like:def set_color(color):mb.config(text=color)print colorWhentheuserselectsamenuitemandset_coloriscalled,itconfigurestheMenubuttontodisplaythe newly-selected color. It also print the color; if you try this example, you can confirm thatset_coloriscalled when you select anitem (and not called when you create the Callable object).

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

Saved successfully!

Ooh no, something went wrong!