id
int64
0
25.6k
text
stringlengths
0
4.59k
9,100
introduction to gui programming when gui program is run it normally begins by creating its main window and all of the main window' widgetssuch as the menu bartoolbarsthe central areaand the status bar once the window has been createdlike server programthe gui program simply waits whereas server waits for client program...
9,101
figure the interest program object--an object that conceptually represents the applicationand something we will return to later on in addition to distinguishing between widgets and windows (also called top-level widgets)the parent-child relationships help ensure that widgets are deleted in the right order and that chil...
9,102
introduction to gui programming self rate tkinter doublevar(self rate set( self years tkinter intvar(self amount tkinter stringvar(tk allows us to create variables that are associated with widgets if variable' value is changed programmaticallythe change is reflected in its associated widgetand similarlyif the user chan...
9,103
for the tkinter scale widgets we give them parent of self as usualand associate variable with each one in additionwe give function (or in this case methodobject reference as their command--this method will be called automatically whenever the scale' value is changedand set its minimum (from_with trailing underscore sin...
9,104
introduction to gui programming right marginand pady (top and bottom marginkeyword arguments giving integer pixel amounts as arguments if widget is allocated more space than it needsthe sticky option is used to determine what should be done with the spaceif not specified the widget will occupy the middle of its allocat...
9,105
that invoked them as their first argumentand we don' want this event sowe use lambda function that accepts but ignores the event and calls the method without the unwanted argument we have also created two keyboard shortcuts--these are key combinations that invoke particular action here we have set ctrl+ and esc and bou...
9,106
introduction to gui programming elseicon "@path "interest xbmapplication iconbitmap(iconapplication title("interest"window mainwindow(applicationapplication protocol("wm_delete_window"window quitapplication mainloop(after defining the class for the main (and in this case onlywindowwe have the code that starts the progr...
9,107
figure the bookmarks program the user interface is all set up in the main window' initializerwhich we will review in five parts because it is fairly long class mainwindowdef __init__(selfparent)self parent parent self filename none self dirty false self data {menubar tkinter menu(self parentself parent["menu"menubar fo...
9,108
introduction to gui programming has left it with some odd corners menu bars created like this do not need to be laid outtk will do that for us filemenu tkinter menu(menubarfor labelcommandshortcut_textshortcut in ("new "self filenew"ctrl+ """)("open "self fileopen"ctrl+ """)("save"self filesave"ctrl+ """)(nonenonenonen...
9,109
image tkinter photoimage(file=imageself toolbar_images append(imagebutton tkinter button(toolbarimage=imagecommand=commandbutton grid(row= column=len(self toolbar_images- except tkinter tclerror as errprint(errtoolbar grid(row= column= columnspan= sticky=tkinter nwwe begin by creating frame in which all of the window' ...
9,110
introduction to gui programming scrollbar tkinter scrollbar(frameorient=tkinter verticalself listbox tkinter listbox(frameyscrollcommand=scrollbar setself listbox grid(row= column= sticky=tkinter nsewself listbox focus_set(scrollbar["command"self listbox yview scrollbar grid(row= column= sticky=tkinter nsself statusbar...
9,111
window self parent winfo_toplevel(window columnconfigure( weight= window rowconfigure( weight= self parent geometry("{ } { }+{ }+{ }format( )self parent title("bookmarks unnamed"the columnconfigure(and rowconfigure(methods allow us to give weightings to grid we begin with the window framegiving all the weight to the fi...
9,112
introduction to gui programming from the first to the last--tkinter end is constant used to signify the last item in contexts where widget can contain multiple items then we clear the dirty flagfilenameand datasince the file is new and unchangedand we set the window title to reflect the fact that we have new but unsave...
9,113
work with since the user cannot change the program' state behind the dialog' backand because they block until they are closed the blocking means that when we create or invoke modal dialog the statement that follows will be executed only when the dialog is closed def filesave(self*ignore)if self filename is nonefilename...
9,114
introduction to gui programming self statusbar after(timeoutself clearstatusbarthis method sets the status bar label' textand if there is timeout ( fivesecond timeout is the default)the method sets up single shot timer to clear the status bar after the timeout period def fileopen(self*ignore)if not self okaytocontinue(...
9,115
except (environmenterrorpickle pickleerroras errtkinter messagebox showwarning("bookmarks error""failed to load { }:\ { }formatself filenameerr)parent=self parentwhen this method is called we know that any unsaved changes have been saved or abandonedso we are free to clear the list box we set the current filename to th...
9,116
introduction to gui programming then we clear the list box and reinsert all the data in sorted order it would be more efficient to simply insert the new bookmark in the right placebut even with hundreds of bookmarks the difference would hardly be noticeable on modern machine at the end we set the dirty flag since we no...
9,117
self listbox delete(indexself listbox focus_set(del self data[nameself dirty true to delete bookmark we must first find out which bookmark the user has chosenso this method begins with the same lines that the mainwindow editedit(method starts with if exactly one bookmark is selected we pop up message box asking the use...
9,118
introduction to gui programming barin the mainwindow class' methods rather than here for the interest program the title never changedso it needed to be set only oncebut for the bookmarks program we change the title text to include the name of the bookmarks file being worked on now that we have seen the implementation o...
9,119
tkinter stringvars are created to keep track of the bookmark' name and urland both are initialized with the passed-in values if the dialog is being used for editing namelabel nameentry urllabel urlentry okbutton cancelbutton figure the bookmarks program' add/edit dialog' layout frame tkinter frame(selfnamelabel tkinter...
9,120
introduction to gui programming in column (the name and url text entry widgetswill grow to take advantage of the extra space similarlywe make the window' column horizontally resizable by setting its weight to if the user changes the dialog' heightthe widgets will keep their relative positions and all of them will be ce...
9,121
after the dialog has been closed the caller checks the accepted variableand if trueretrieves the name and url that were added or edited thenonce the mainwindow editadd(or mainwindow editedit(method has finishedthe addeditform object goes out of scope and is scheduled for garbage collection summary ||this gave you flavo...
9,122
introduction to gui programming note that while on unix-like systems file suffix of dbm is fineon windows each dbm "fileis actually three files so for windows file dialogs the pattern should be dbm dat and the default extension dbm dat--but the actual filename should have suffix of dbmso the last four characters must b...
9,123
epilogue if you've read at least the first six and either done the exercises or written your own python programs independentlyyou should be in good position to build up your experience and programming skills as far as you want to go--python won' hold you backto improve and deepen your python language skillsif you read ...
9,124
|||this is small selected annotated bibliography of programming-related books most of the books listed are not python-specificbut all of them are interestinguseful--and accessible clean code robert martin (prentice hall isbn this book addresses many "tacticalissues in programminggood namingfunction designrefactoringand...
9,125
selected bibliography perl--which probably has more regular expression features than any other tool howeversince python supports large subset of what perl provides (plus python' own ? extensions)the book is still useful to python programmers parsing techniquesa practical guidesecond edition dick gruneceriel jacobs (spr...
9,126
all functions and methods are listed under their class or moduleand in most cases also as top-level terms in their own right for modules that contain classeslook under the class for its methods where method or function name is close enough to conceptthe concept is not usually listed for examplethere is no entry for "sp...
9,127
index >>(int shift right augmented asadd((set type) signment operator) (decorator operator) - [(indexing operatoritem access operatorslicing operator) \ (newline characterstatement terminator) (bitwise xor operator) ^(bitwise xor augmented assignment operator) (underscore) (bitwise or operator) |(bitwise or augmented a...
9,128
askopenfilename((tkinter filedialog module) asksaveasfilename((tkinter filedialog module) askyesno((tkinter messagebox module) askyesnocancel((tkinter messagebox module) assert (statement) - assertionerror (exception) assertionsregex - associativity - ast (abstract syntax tree) asynchat module asyncore module atan((mat...
9,129
index built-in abs() all() any() ascii() bin() bool() chr() @classmethod() compile() complex() delattr() dict() dir() divmod() enumerate() - eval() exec() - filter() float() format() frozenset() getattr() globals() hasattr() hash() help() hex() id() __import__() input() int() isinstance() issubclass() iter() len() list...
9,130
bytearray type (cont fromhex() index() insert() isalnum() isalpha() isdigit() islower() isspace() istitle() isupper() join() ljust() lower() lstrip() methodstable of partition() pop() remove() replace() reverse() rfind() rindex() rjust() rpartition() rsplit() rstrip() split() splitlines() startswith() strip() swapcase(...
9,131
index call((subprocess module) callablesee functions and methods callable abc (collections module) callable objects @classmethod() clear(dict type set type close(capitalize(bytearray type bytes type str type connection object coroutines cursor object file object closed attribute (file object) closures cmath module code...
9,132
comparing objects comparing strings - comparisonssee and >operators compile(built-in re module __complex__() complex((built-in) complex abc (numbers module) complex type - complex((built-in) conjugate() imag attribute real attribute composing functions - - composition comprehensionssee under dictlistand set types compr...
9,133
count((cont bytes type list type str type tuple type cprofile module - create table (sql statement) creationof objects csv (extension) csv module csv html py (example) - csv html _opt py (example) ctypes module curryingsee partial function application cursor((connection object) cursor object arraysize attribute close()...
9,134
deep copyingsee copying collections deepcopy((copy module) def (statement) - default arguments defaultdict type (collections module) - degrees((math module) del (statement) __del__() __delattr__() delattr((built-in) delegation delete (sql statement) __delitem__(([]) deque type (collections module) description attribute...
9,135
duck typingsee dynamic typing dump((pickle module) dumps((pickle module) duplicateseliminating dvds-dbm py (example) - dvds-sql py (example) - dynamic code execution - dynamic functions dynamic imports - dynamic typing index environment variable lang path pythondontwritebytecode pythonoptimize pythonpath environmenterr...
9,136
example (cont dvds-sql py - external_sites py externalstorage py finddup py findduplicates- py - first-order-logic py - - fuzzybool py - fuzzyboolalt py - generate_grid py - generate_test_names py generate_test_names py generate_usernames py - grepword- py grepword- py - grepword py grepword- py - html text py image py...
9,137
index expand((match object) expandtabs(bytearray type bytes type str type expat xml parser expressionconditional expressionsboolean extend(bytearray type list type extending lists extension bz csv gz ini pls py pyc and pyo pyw svg tartar gztar bz tgz wav xpm zip external_sites py (example) externalstorage py (example) ...
9,138
filescomparing filescompressing and uncompressing filesformat comparison - filesrandom accesssee binary files filestemporary filestext - filesxml - filter((built-in) filtering - finally (statement)see try statement find(bytearray type bytes type str type - findall(re module regex object finddup py (example) findduplica...
9,139
functions (cont lambdasee lambda statement local - module object reference to parameterssee argumentsfunction recursive - see also functors functionsintrospection-relatedtable of functionsiteratortable of functionsnestedsee local functions functionstable of (math module) functionstable of (re module) functools module p...
9,140
hasattr((built-in) __hash__() hash((built-in) hashable abc (collections module) hashable objects heapq module - help((built-in) hex(built-in float type hexadecimal numbers html entities module html escapes html parser module html text py (example) http package hypot((math module) __iadd__((+=) __iand__((&=) id((built-i...
9,141
index int type (cont int((built-in) integral abc (numbers module) interest-tk pyw (example) - internationalization internet message access protocol (imap ) interpreter options intersection_update((set type) intersection(frozenset type set type introspection intvar type (tkinter module) __invert__((~) invertinga diction...
9,142
iterator abc (collections module) iterators - functions and operatorstable of itertools module __ixor__((^=) join(bytearray type bytes type os path module str type json module key bindings keyboard accelerators keyboard focus keyboard shortcuts keyboardinterrupt (exception) keyerror (exception) keys((dict type) keyword...
9,143
index locale module setlocale() localization locals((built-in) localtime((time module) lock type (threading module) log((math module) log ((math module) log ((math module) logging module logicshort-circuit logical operatorssee andorand not lookuperror (exception) loopingsee for loop and while loop lower(bytearray type ...
9,144
math module (cont fmod() frexp() fsum() functionstable of hypot() isinf() isnan() ldexp() log() log () log () modf() pi (constant) pow() radians() sin() sinh() sqrt() tan() tanh() trunc() max((built-in) maxunicode attribute (sys module) md (message digest algorithm) membership testingsee in operator memoizing memory ma...
9,145
index number abc (numbers module) numbers module __name__ (attribute) classestable of complex abc integral abc number abc rational abc real abc numeric operators and functionstable of name((unicodedata module) name attribute (file object) name conflictsavoiding name mangling namedtuple type (collections module) - namee...
9,146
or (logical operator) ord((built-in) ordered collectionssee list and tuple types ordereddict type (collections module) - os module - chdir() environ mapping getcwd() listdir() makedirs() mkdir() remove() removedirs() rename() rmdir() sep attribute stat() system() walk() os path module - abspath() basename() dirname() e...
9,147
pickle module (cont loads() pickles - pipelines - pipessee subprocess module placeholderssql platform attribute (sys module) playlists py (example) - - - pls (extension) ply p_error() precedence variable states variable - t_error() t_ignore variable t_newline() tokens variable pointerssee object references policyerror ...
9,148
pyparsing (cont regex() restofline skipto() suppress() word() zeroormore() pyqt pythondontwritebytecode (environment variable) python enhancement proposalssee peps python shell (idle or interpreter) pythonoptimize (environment variable) pythonpath (environment variable) pyw (extension) quadratic py (example) - qualifie...
9,149
regex (cont flags greedy groups - matchsee match object nongreedy quantifiers - special characters regex object findall() finditer() flags attribute groupindex attribute match() methodstable of pattern attribute search() split() sub() subn() see also re module and match object relational integrity relative imports remo...
9,150
rstrip((cont bytes type str type __rsub__((-) __rtruediv__((/) run((thread type) __rxor__((^) sample((random module) sax (simple api for xml)see xml sax module scalable vector graphics (svg) scale type (tkinter module) scanning scrollbar type (tkinter module) search(re module regex object searching seek((file object) s...
9,151
index shelve module open() sync() sortkey py (example) short-circuit logic shortcutkeyboard showwarning((tkinter messagebox module) shutil module simple api for xml (sax)see xml sax module simple mail transfer protocol (smtp) sin((math module) single shot timer sinh((math module) site-packages directory sized abc (coll...
9,152
special method (cont __imod__((%=) __imul__((*=) __index__() __init__() __int__() __invert__((~) __ior__((|=) __ipow__((**=) __irshift__((>>=) __isub__((-=) __iter__() __ixor__((^=) __le__((<=) __len__() __lshift__((<<) __lt__((<) __mod__((%) __mul__((*) __ne__((!=) __neg__((-) __new__() __next__() __or__((|) __pos__((...
9,153
contents tic-tac-toe example further topics exercises ii graphics gui programming with tkinter basics labels grid entry boxes buttons global variables tic-tac-toe gui programming ii frames colors images canvases check buttons and radio buttons text widget scale widget gui events event examples gui programming iii title...
9,154
vii iii intermediate topics miscellaneous topics iii mutability and references tuples sets unicode sorted if-else operator continue eval and exec enumerate and zip copy more with strings miscellaneous tips and tricks running your python programs on other computers useful modules importing modules dates and times workin...
9,155
contents using the python shell as calculator working with functions first-class functions anonymous functions recursion mapfilterreduceand list comprehensions the operator module more about function arguments the itertools and collections modules permutations and combinations cartesian product grouping things miscella...
9,156
my goal here is for something that is partly tutorial and partly reference book like how tutorials get you up and running quicklybut they can often be little wordy and disorganized reference books contain lot of good informationbut they are often too terseand they don' often give you sense of what is important my aim h...
9,157
contents perfecttic-tac-toe game the final of part ii covers bit about the python imaging library part iii contains lot of the fun and interesting things you can do with python if you are structuring one-semester course around this bookyou might want to pick few topics in part iii to go over this part of the book could...
9,158
getting started this will get you up and running with pythonfrom downloading it to writing simple programs installing python go to www python org and download the latest version of python (version as of this writingit should be painless to install if you have mac or linuxyou may already have python on your computerthou...
9,159
getting started either do that or start up idle and open the file through the file menu keyboard shortcuts the following keystrokes work in idle and can really speed up your work keystroke result ctrl+ copy selected text ctrl+ cut selected text ctrl+ paste ctrl+ undo the last keystroke or group of keystrokes ctrl+shift...
9,160
argument to the print function is the calculation python will do the calculation and print out the numerical result this program may seem too short and simple to be of much usebut there are many websites that have little utilities that do similar conversionsand their code is not much more complicated than the code here...
9,161
getting started getting input the input function is simple way for your program to get information from people using your program here is an examplename input'enter your name'print'hello'namethe basic structure is variable name input(message to userthe above works for getting text from the user to get numbers from the ...
9,162
optional arguments there are two optional arguments to the print function they are not overly important at this stage of the gameso you can safely skip over this sectionbut they are useful for making your output look nice sep python will insert space between each of the arguments of the print function there is an optio...
9,163
getting started temp eval(input'enter temperature in celsius')print'in fahrenheitthat is ' / *temp+ one of the major purposes of variable is to remember value from one part of program so that it can be used in another part of the program in the case abovethe variable temp stores the value that the user enters so that w...
9,164
variable names there are just couple of rules to follow when naming your variables variable names can contain lettersnumbersand the underscore variable names cannot contain spaces variable names cannot start with number case matters--for instancetemp and temp are different it helps make your program more understandable...
9,165
getting started ask the user to enter number use the sep optional argument to print out and each separated by three dasheslike below enter number --- --- --- --- write program that asks the user for weight in kilograms and converts it to pounds there are pounds in kilogram write program that asks the user to enter thre...
9,166
for loops probably the most powerful thing about computers is that they can repeat things over and over very quickly there are several ways to repeat things in pythonthe most common of which is the for loop examples example the following program will print hello ten timesfor in range( )print'hello 'the structure of for...
9,167
for loops enter number the square of your number is enter number the square of your number is enter number the square of your number is the loop is now done since the second and third lines are indentedpython knows that these are the statements to be repeated the fourth line is not indentedso it is not part of the loop...
9,168
the loop variable there is one part of for loop that is little trickyand that is the loop variable in the example belowthe loop variable is the variable the output of this program will be the numbers each printed on its own line for in range( )print(iwhen the loop first startspython sets the variable to each time we lo...
9,169
for loops if we want the list of values to start at value other than we can do that by specifying the starting value the statement range( , will produce the list this brings up one quirk of the range function--it stops one short of where we think it should if we wanted the list to contain the numbers through (including...
9,170
suppose we want to make triangle instead we can accomplish this with very small change to the rectangle program looking at the programwe can see that the for loop will repeat the print statement four timesmaking the shape four rows tall it' the that will need to change the key is to change the to + each time through th...
9,171
for loops the fibonacci numbers are the sequence belowwhere the first two numbers are and each number thereafter is the sum of the two preceding numbers write program that asks the user how many fibonacci numbers to print and then prints that many use for loop to print box like the one below allow the user to specify h...
9,172
write program that prints giant letter like the one below allow the user to specify how large the letter should be ****
9,173
for loops
9,174
numbers this focuses on numbers and simple mathematics in python integers and decimal numbers because of the way computer chips are designedintegers and decimal numbers are represented differently on computers decimal numbers are represented by what are called floating point numbers the important thing to remember abou...
9,175
numbers operator description addition subtraction multiplication division *exponentiation /integer division modulo (remainderexponentiation python uses *for exponentiation the caret^is used for something else integer division the integer division operator//requires some explanation basicallyfor positive numbers it beha...
9,176
order of operations exponentiation gets done firstfollowed by multiplication and division (including /and %)and addition and subtraction come last the classic math class mnemonicpemdas (please excuse my dear aunt sally)might be helpful this comes into play in calculating an average say you have three variables xyand za...
9,177
numbers from math import sinpi print'pi is roughly 'piprint'sin( 'sin( )pi is roughly sin( built-in math functions there are two built in math functionsabs (absolute valueand round that are available without importing the math module here are some examplesprint(abs(- )print(round( )print(round( - ) the round function t...
9,178
** for in range( , ) / ** from math import factorial( the second example here sums the numbers / / / the result is stored in the variable to inspect the value of that variablejust type its name and press enter inspecting variables is useful for debugging your programs if program is not working properlyyou can type your...
9,179
numbers write program that asks the user for number of seconds and prints out how many minutes and seconds that is for instance seconds is minutes and seconds [hintuse the /operator to get minutes and the operator to get seconds write program that asks the user for an hour between and and for how many hours in the futu...
9,180
year (all four digitsm ( + mod ( mod mod mod mod ( mmod ( nmod easter is either march ( eor april ( there is an exception if and in this caseeaster falls one week earlier on april there is another exception if and or in this caseeaster falls one week earlier on april write program that asks the user to enter year and p...
9,181
numbers
9,182
if statements quite often in programs we only want to do something provided something else is true python' if statement is what we need simple example let' try guess- -number program the computer picks random numberthe player tries to guessand the program tells them if they are correct to see if the player' guess is co...
9,183
if statements conditional operators the comparison operators are ==>=<=and !that last one is for not equals here are few examplesexpression description if > if is greater than if >= if is greater than or equal to if == if is if != if is not there are three additional operators used to construct more complicated conditi...
9,184
the first statement is the correct one if is any value between and then the statement will be true the idea is that has to be both greater than and less than on the other handthe second statement is not what we want because for it to be trueeither has to be greater than or has to be less than but every number satisfies...
9,185
if statements elif grade>= print' 'elseprint' 'with the separate if statementseach condition is checked regardless of whether it really needs to be that isif the score is the first program will print an but then continue on and check to see if the score is bcetc which is bit of waste using elifas soon as we find where ...
9,186
generate random number between and ask the user to guess the number and print message based on whether they get it right or not store charges $ per item if you buy less than items if you buy between and itemsthe cost is $ per item if you buy or more itemsthe cost is $ per item write program that asks the user how many ...
9,187
if statements write program that lets the user play rock-paper-scissors against the computer there should be five roundsand after those five roundsyour program should print out who won and lost or that there is tie
9,188
miscellaneous topics this consists of several common techniques and some other useful information counting very often we want our programs to count how many times something happens for instancea video game may need to keep track of how many turns player has usedor math program may want to count how many numbers have sp...
9,189
miscellaneous topics line does we set it to to indicate that at the start of the program no numbers greater than have been found counting is an extremely common thing the two things involved are count= -start the count at count=count+ -increase the count by example this modification of the previous example counts how m...
9,190
example this program will add up the numbers from to the way this works is that each time we encounter new numberwe add it to our running totals for in range( , ) print'the sum is 'sexample this program that will ask the user for numbers and then computes their average for in range( )num eval(input'enter number') num p...
9,191
miscellaneous topics flag variables flag variable can be used to let one part of your program know when something happens in another part of the program here is an example that determines if number is prime num eval(input'enter number')flag for in range( ,num)if num% == flag if flag== print'not prime 'elseprint'prime '...
9,192
comments comment is message to someone reading your program comments are often used to describe what section of code does or how it worksespecially with tricky sections of code comments have no effect on your program single-line comments for single-line commentuse the character slightly sneaky way to get two values at ...
9,193
miscellaneous topics condition of an if statementyou can put print statement into the if block to see if the condition is being triggered here is an example from the part of the primes program from earlier in this we put print statement into the for loop to see exactly when the flag variable is being setflag num eval(i...
9,194
example compare the following two programs from random import randint from random import randint rand_num randint( , for in range( )print'hello '*rand_numfor in range( )rand_num randint( , print'hello '*rand_numhello hello hello hello hello hello hello hello hello hello hello hello hello hello hello hello hello hello h...
9,195
miscellaneous topics indentation matters common mistake is incorrect indentation suppose we take the above and indent the last line the program will still runbut it won' run as expected from random import randint count for in range( )num randint( if num% == count=count+ print'number of multiples of 'countwhen we run it...
9,196
write program that asks the user to enter number and prints the sum of the divisors of that number the sum of the divisors of number is an important function in number theory number is called perfect number if it is equal to the sum of all of its divisorsnot including the number itself for instance is perfect number be...
9,197
miscellaneous topics knows behind which door the prize liesthen opens up one of the doors that doesn' contain the prize there are now two doors leftand monty gives you the opportunity to change your choice should you keep the same doorchange doorsor does it not matter(awrite program that simulates playing this game tim...
9,198
strings strings are data type in python for dealing with text python has number of powerful features for manipulating strings basics creating string string is created by enclosing text in quotes you can use either single quotes'or double quotesa triple-quote can be used for multi-line strings here are some exampless 'h...
9,199
strings concatenation and repetition the operators and can be used on strings the operator combines two strings this operation is called concatenation the repeats string certain number of times here are some examples expression result 'ab'+'cd'abcd' '+' '+' ' 'hi'* 'hihihihiexample if we want to print long row of dashe...