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.6. Packing widgets 187self.bu(text='Quit', command=self.quit)self.bu(text='Make Turtle', command=self.make_turtle)self.bu(text='Clear', command=self.clear)self.endgr()gr creates the grid; the argument is the number of columns. Widgets in the grid are laid out left-toright,top-to-bottom.The first button uses self.canvas.dump as a callback; the second uses self.quit. These arebound methods, which means they are associated with a particular object. When they are invoked,they are invoked onthe object.The next widget inthe column isarow Frame that contains aButton and anEntry:self.row([0,1], pady=30)self.bu(text='Run file', command=self.run_file)self.en_file = self.en(text='snowflake.py', width=5)self.endrow()The first argument to row is a list of weights that determines how extra space is allocated betweenwidgets. The list [0,1] means that all extra space is allocated to the second widget, which is theEntry. If you run this code and resize the window, you will see that the Entry grows and the Buttondoesn’t.The optionpady“pads” thisrow inthe ydirection, adding 30pixels of space above and below.endrow ends this row of widgets, so subsequent widgets are packed in the column Frame. Gui.pykeeps astack of Frames:• When you use row, col or gr to create a Frame, it goes on top of the stack and becomes thecurrent Frame.• When you use endrow, endcol or endgr to close a Frame, it gets popped off the stack andthe previous Frame on thestack becomes thecurrent Frame.The method run_file reads the contents of the Entry, uses it as a filename, reads the contents andpasses it to run_code. self.inter is an Interpreter object that knows how to take a string andexecute itas <strong>Python</strong> code.def run_file(self):filename = self.en_file.get()fp = open(filename)source = fp.read()self.inter.run_code(source, filename)The lasttwowidgets areaText widget and aButton:self.te_code = self.te(width=25, height=10)self.te_code.insert(END, 'world.clear()\n')self.te_code.insert(END, 'bob = Turtle(world)\n')self.bu(text='Run code', command=self.run_text)run_text is similar torun_file except that it takes the code from the Text widget instead of fromafile:

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

Saved successfully!

Ooh no, something went wrong!