programming for engineers in python
DESCRIPTION
Programming for Engineers in Python. Recitation 11. Plan. GUI Swampy Text widgets PyPad. Install Swampy. Download Swampy: http://greenteapress.com/thinkpython/swampy/swampy-2.0.python2.zip Unzip to C:\ Python27\Lib\site-packages - PowerPoint PPT PresentationTRANSCRIPT
PowerPoint Presentation
Recitation 11
Programming for Engineers in Python1PlanGUISwampyText widgetsPyPad22Install Swampy3Download Swampy:http://greenteapress.com/thinkpython/swampy/swampy-2.0.python2.zipUnzip to C:\Python27\Lib\site-packagesNow you should have a directory C:\Python27\Lib\site-packages\swampy-2.0Download this file http://db.tt/gQqPvRok (it might open as a text file, right click and choose Save as) and also put it in C:\Python27\Lib\site-packages, making sure its name is swampy.pthNow you should have a file C:\Python27\Lib\site-packages\swampy.pthCheck Swampy was installed4Open the shell (IDLE)Run the following commands to check that Swampy is working:>>> import Tkinter>>> from Gui import *>>> g=Gui()>>> g.mainloop()If you see a window like this -> then the installation worked
GUI - reminder5Graphical User InterfaceThe part of the program that communicates with the human userComputer Human: graphics (sometimes audio & even vibrations)Human Computer: keyboard & mouse (sometimes even touchscreen & microphone)In many applications this is the most important part of the program
History of GUI6http://www.youtube.com/watch?v=TZGGUrom1MgWidgets7In class:ButtonLabelCanvas
More widgets!8Textual input widgets:
Entry single lineentry_example.py: https://gist.github.com/1523427
Text multiple linestext_example.py: https://gist.github.com/1523471
Think Python 19.5
More complex example9Change the color of a circle based on the color name given by the usercircle_demo.py: thinkpython.com/code/circle_demo.py
Think Python 19.5 pg. 185PyNote a Python Notepad10
Packing 11>>> g = Gui() >>> g.title('PyNote 0.1')
Creates the GUI & title
Packing 12>>> g.col(weights=[1,0])
Creates a column that holds widgets
Weights later
Packing 13>>> g.st()
st:Scrollable text widget
Packing 14
>>> g.row(weights=[1,0,0,0])Creates a row that holds widgets
The weights option determines which widget is resized and by how much when the window is resizedResizing15With weights=[1,0,0,0]
Without specifying weights
Packing 16filename = g.en(text='filename.txt', width=16)g.bu(text='...', command=browse)g.bu(text='Save', command=save)g.bu(text='Load', command=load)g.bu(text='New', command=new)g.bu(text='Quit', command=quit_)
g.bu: button widgetg.en: entry widget (one line of text)
Check if a file exists17os.path.exists(filename)Returns True if file exists, False if it does not
Command18g.bu(text='Save', command=save)
def save(): '''Saves the current note in a file''' if exists(filename.get()): # exists is os.path.exists if not tkMessageBox.askyesno ('Save','File already exists, do you want to overwrite?'): return f = open(filename.get(),'w') f.write(textbox.text.get(0.0, END)) f.close() tkMessageBox.showinfo('Save','File saved: +filename.get())Event driven programming19Nothing happens until the user initiates an eventWhen the user clicks the button the command is calledNow the GUI is frozen until the command returnsWhen it returns, the GUI is released
>>> def freeze():time.sleep(5)>>> g=Gui()>>> g.bu(text=Freeze!,command=freeze)>>> g.mainloop()
tkMessageBox20Creates a message box that asks the user a question or gives him informationUsually with a button or twoExamples:
tkMessageBox.showinfo('Load','File does not exist: '+filename.get())tkMessageBox.askyesno('Quit?','Do you want to quit?')tkMessageBox.askyesno('Save','File already exists, do you want to overwrite?')http://www.tutorialspoint.com/python/tk_messagebox.htm
21tkMessageBox.askyesno('Save','File already exists, do you want to overwrite?')
tkMessageBox.askyesno('Quit?','Do you want to quit?')22
tkMessageBox.showinfo('Load','File does not exist: + filename.get())23Load command24def load(): '''Opens a file to the text widget''' if not exists(filename.get()): tkMessageBox.showinfo('Load','File does not exist: ' +filename.get()) return new() # delete previous note from text widget f = open(filename.get()) t = f.read() textbox.text.insert(0.0, t) f.close()File dialog box25We can get the file by writing/copy-pasting its name, but its easier with a file dialog box:t = tkFileDialog.askopenfilename()
File dialog box contd.26We use the dialog box in the browse function which is called by the buttondef browse(): '''opens a file dialog and sets its result to the filename entry''' t = tkFileDialog.askopenfilename() if t: filename.delete(0,END) filename.insert(0,t)
Exit the GUI27User:By clicking the windows X iconBy pressing Ctrl-C in the shellProgram:By calling g.destroy()Example quit_() function (_ is used in the name because quit is a python word):def quit_(): '''asks the user if he wants to quit''' if tkMessageBox.askyesno ('Quit?','Do you want to quit?'): g.destroy() # this actually quits the GUIReverse text28We create a button that will reverse all the words in the text
Reverse text29We create a button that will reverse all the words in the text
Reverse word30def reverse_word(word): return word[-1::-1].capitalize()
We used capitalize so that the words will look nice:January -> Yraunaj and not yraunaJ Reverse text31def reverse(): orig = textbox.text.get(0.0, END) new() # delete the current text for line in orig.split('\n'): for word in line.split(' '): textbox.text.insert(END, reverse_word(word)) textbox.text.insert(END, ' ') # is a space textbox.text.insert(END, '\n') # newlineReverse button32g.bu(text='Reverse', command=reverse)
Add functionality, then add a buttonWe can now add other functionalities (if time permits):Count wordsCount characters (frequency counter)Count linesDecipher (HW 5)Markov analysis (HW 4)Translate (http://www.catonmat.net/blog/python-library-for-google-translate/)