id
int64
0
25.6k
text
stringlengths
0
4.59k
9,300
gui programming with tkinter label grid(row= column= label grid(row= column= label grid(row= column= columnspan= label grid(row= column= label grid(row= column= label label label label label spacing to add extra space between widgetsthere are optional arguments padx and pady important note any time you create widgetto ...
9,301
ok_button button(text'ok 'to get the button to do something when clickeduse the command argument it is set to the name of functioncalled callback function when the button is clickedthe callback function is called here is an examplefrom tkinter import def callback()label configure(text'button clicked 'root tk(label labe...
9,302
gui programming with tkinter buttons[igrid(row= column=imainloop(we note few things about this program firstwe set buttons=[ ]* this creates list with things in it we don' really care what thoset things are because they will be replaced with buttons an alternate way to create the list would be to set buttons=[and use t...
9,303
but in the short programs that we will be writingwe should be okay object-oriented programming provides an alternative to global variables tic-tac-toe using tkinterin only about lines we can make working tic-tac-toe programfrom tkinter import def callback( , )global player if player =' ' [ ][cconfigure(text ' 'player '...
9,304
gui programming with tkinter correcting the problems to correct the problem about being able to change cell that already has something in itwe need to have way of knowing which cells have 'swhich have 'sand which are empty one way is to use button method to ask the button what its text is another waywhich we will do he...
9,305
player ' mainloop(we have not added much to the program most of the new action happens in the callback function every time someone clicks on cellwe first check to see if it is empty (that the corresponding index in states is )and if it iswe display an or on the screen and record the new value in states many games have ...
9,306
gui programming with tkinter puter player that moves randomly that would take about lines of code to make an intelligent computer player is not too difficult such computer player should look for two ' or ' in row in order to try to win or blockas well avoid getting put into no-win situation from tkinter import def call...
9,307
[ , , ]states [[ , , ][ , , ][ , , ]for in range( )for in range( ) [ ][jbutton(font='verdana ' )width= bg'yellow 'command lambda = , =jcallback( , ) [ ][jgrid(row icolumn jplayer ' stop_game false mainloop(
9,308
gui programming with tkinter
9,309
gui programming ii in this we cover more basic gui concepts frames let' say we want small buttons across the top of the screenand big ok button below themlike belowwe try the following codefrom tkinter import root tk(alphabet 'abcdefghijklmnopqrstuvwxyz buttons [ ]* for in range( )buttons[ibutton(text=alphabet[ ]button...
9,310
gui programming ii the problem is with column there are two widgets therethe button and the ok buttonand tkinter will make that column big enough to handle the larger widgetthe ok button one solution to this problem is shown belowok_button grid(row= column= columnspan= another solution to this problem is to use what is...
9,311
parts of blue and green create shades of turquoise equal parts of all three create shades of gray black is when all three components have values of and white is when all three components have values of varying the values of the components can produce up to million colors there are number of resources on the web that al...
9,312
gui programming ii here are some examples of putting the image into widgetslabel label(image=cheetah_imagebutton button(image=cheetah_imagecommand=cheetah_callback()you can use the configure method to set or change an imagelabel configure(image=cheetah_imagefile types one unfortunate limitation of tkinter is the only c...
9,313
canvas create_rectangle( , , , canvas create_oval( , , , fill'blue 'canvas create_line( , , , fill'green 'the rectangle is here to show that lines and ovals work similarly to rectangles the first two coordinates are the upper left and the second two are the lower right to get circle with radius and center ( , )we can c...
9,314
gui programming ii the one thing to note here is that we have to tie the check button to variableand it can' be just any variableit has to be special kind of tkinter variablecalled an intvar this variableshow_totalswill be when the check button is unchecked and when it is checked to access the value of the variableyou ...
9,315
here are few common commandsstatement description textbox get( ,endreturns the contents of the text box textbox delete( ,enddeletes everything in the text box textbox insert(end,'hello'inserts text at the end of the text box one nice option when declaring the text widget is undo=truewhich allows ctrl+ and ctrl+ to undo...
9,316
gui programming ii works just like with buttons gui events often we will want our programs to do something if the user presses certain keydrags something on canvasuses the mouse wheeletc these things are called events simple example the first gui program we looked at back in section was simple temperature converter any...
9,317
attribute description keysym the name of the key that was pressed xy the coordinates of the mouse pointer delta the value of the mouse wheel key events for key eventsyou can either have specific callbacks for different keys or catch all keypresses and deal with them in the same callback here is an example of the latter...
9,318
gui programming ii tkinter name common name enter key tab key spacebar page uppage down arrow keys homeend insertdelete caps locknumber lock left and right control keys left and right alt keys left and right shift keys most printable keys can be captured with their nameslike belowroot bind' 'callbackroot bind' 'callbac...
9,319
move + elif event keysym='left 'move -= canvas coords(rect, +move, , +move, root tk(root bind'callbackcanvas canvas(width= ,height= canvas grid(row= ,column= rect canvas create_rectangle( , , , ,fill'blue 'move mainloop(example here is an example program demonstrating mouse events the program starts by drawing rectangl...
9,320
gui programming ii def _motion_event(event)global _dragx mouse_xmouse_y event event if not _dragmouse_x mouse_y _drag true return +=( -mouse_xx +=( -mouse_xy +=( -mouse_yy +=( -mouse_ycanvas coords(rect, , , , mouse_x mouse_y def _release_event(event)global _drag _drag false root=tk(label label(canvas canvas(width= hei...
9,321
here are few notes about how the program works firstevery time the mouse is moved over the canvasthe mouse_motion_event function is called this function prints the mouse' current coordinates which are contained in the event attributes and the wheel_event function is called whenever the user uses the mouse (scrollingwhe...
9,322
gui programming ii finallythe use of global variables here is little messy if this were part of larger projectit might make sense to wrap all of this up into class
9,323
gui programming iii this contains few more gui odds and ends title bar the gui window that tkinter creates says tk by default here is how to change itroot title'your title ' disabling things sometimes you want to disable button so it can' be clicked buttons have an attribute state that allows you to disable the widget ...
9,324
gui programming iii this can be used with buttonscanvasesetc and it can be used with any of their propertieslike bgfgstateetc as shortcuttkinter overrides the [operatorsso that label['text'accomplishes the same thing as the example above message boxes message boxes are windows that pop up to ask you question or say som...
9,325
function return value (based on what user clicksshowinfo always returns 'okaskokcancel ok--true askquestion yes--'yesno--'noaskretrycancel retry--true cancel or window closed--false askyesnocancel yes--true showerror always returns 'okshowwarning always returns 'okcancel or window closed--false no--false anything else-...
9,326
gui programming iii ifin that functionyou want to change something on the screenpause for short whileand then change something elseyou will need to tell tkinter to update the screen before the pause to do thatjust use thisroot update(if you only want to update certain widgetand nothing elseyou can use the update method...
9,327
here are the most useful dialogsdialog description askopenfilename opens typical file chooser dialog askopenfilenames like previousbut user can pick more than one file asksaveasfilename opens typical file save dialog askdirectory opens directory chooser dialog the return value of askopenfilename and asksaveasfilename i...
9,328
gui programming iii 'all files ''')] open(filenameread(textbox insert( smainloop( menu bars we can create menu barlike the one belowacross the top of window here is an example that uses some of the dialogs from the previous sectionfrom tkinter import from tkinter filedialog import def open_callback()filename askopenfil...
9,329
you can add widgets to the new window the first argument when you create the widget needs to be the name of the windowlike below new_window toplevel(label label(new_windowtext'hi 'label grid(row= column= pack there is an alternative to grid called pack it is not as versatile as gridbut there are some places where it is...
9,330
gui programming iii here is simple example that ties two labels to the same stringvar there is also button that when clicked will alternate the value of the stringvar (and hence the text in the labelsfrom tkinter import def callback()global count set'goodbye if count% == else 'hello 'count += root tk(count stringvar( s...
9,331
further graphical programming python vs python as of this writingthe most recent version of python is and all the code in this book is designed to run in python the tricky thing is that as of version python broke compatibility with older versions of python code written in those older versions will not always work in py...
9,332
further graphical programming input the python equivalent of the input function is raw_input range the range function can be inefficient with very large ranges in python the reason is that in python if you use range( )python will create list of million numbers the range statement in python is more efficient and instead...
9,333
importing future behavior in python the following import allows us to use python ' division behavior from __future__ import division there are many other things you can import from the future the python imaging library the python imaging library (pilcontains useful tools for working with images as of this writingthe pi...
9,334
further graphical programming for in range(photo width())for in range(photo height())red,green,blue pix[ ,javg (red+green+blue)// pix[ , (avgavgavgphoto=imagetk photoimage(imagecanvas create_image( , ,image=photo,anchor=nwdef load_file(filename)global imagephoto image=image open(filenameconvert'rgb 'photo=imagetk photo...
9,335
putdata if you are interested drawing mathematical objects like fractalsplotting points pixelby-pixel can be very slow in python one way to speed things up is to use the putdata method the way it works is you supply it with list of rgb pixel valuesand it will copy it into your image here is program that plots grid of r...
9,336
further graphical programming from pil import imageimagetkimagedraw root tk(canvas canvas(width= height= canvas grid(image=image new(mode'rgb ',size=( , )draw imagedraw draw(imagedraw rectangle([( , ),( )],fill'# ' [(randint( , )randint( )for in range( )draw point(lfill'yellow 'photo=imagetk photoimage(imagecanvas crea...
9,337
intermediate topics
9,338
miscellaneous topics iii in this we examine variety of useful topics mutability and references if is list and is stringthen [ gives the first element of the list and [ the first element of the string if we want to change the first element of the list to [ ]= will do it but we cannot change string this way the reason ha...
9,339
miscellaneous topics iii [ ]= print' is now'lcopy'copyl is now[ copy[ we can see that the list code did not work as we might have expected when we changed lthe copy got changed as well as mentioned in the proper way to make copy of is copy= [:the key to understanding these examples is references references everything i...
9,340
tuples tuple is essentially an immutable list below is list with three elements and tuple with three elementsl [ , , ( , , tuples are enclosed in parenthesesthough the parentheses are actually optional indexing and slicing work the same as with lists as with listsyou can get the length of the tuple by using the len fun...
9,341
miscellaneous topics iii { , , , , recall that curly braces are also used to denote dictionariesand {is the empty dictionary to get the empty setuse the set function with no argumentslike thiss set(this set function can also be used to convert things to sets here are two examplesset([ , , , , , , , , ]set'this is test ...
9,342
[ , , , , , , , , list(set( )after thisl will equal [ , , , , examplewordplay here is an example of an if statement that uses set to see if every letter in word is either an abcdor eif set(wordcontainedin'abcde ') unicode it used to be computers could only display different characterscalled ascii characters in this sys...
9,343
miscellaneous topics iii sorted first definitionan iterable is an object that allows you to loop through its contents iterables include liststuplesstringsand dictionaries there are number of python methods that work on any iterable the sorted function is built-in function that can be used to sort an iterable as first e...
9,344
statement and jumps back up to the start of the loopadvancing the loop counter as necessary here is an example the code on the right accomplishes the same thing as the code on the left for in lif not in foundcount+= if [ ]=' 'count += for in lif in foundcontinue count+= if [ ]=' 'count += the continue statement is some...
9,345
miscellaneous topics iii one nice use of the exec function is to let program' user define math functions to use while the program is running here is the code to do thats input'enter function'exec'def ( )return si have used this code in graph plotting program that allows users to enter equations to be graphedand have us...
9,346
the for loop above is equivalent to the followingfor in range(len( ))print( + [ ]the enumerate code can be shorter or clearer in some situations here is an example that returns list of the indices of all the ones in string[ for ( ,cin enumerate(sif =' 'zip the zip function takes two iterables and "zipsthem up into sing...
9,347
miscellaneous topics iii the deepcopy method is used in this type of situation to only copy the values and not the references here is how it would workfrom copy import deepcopy deepcopy( more with strings there are few more facts about strings that we haven' yet talked about translate the translate method is used to tr...
9,348
table for both encoding and decodingusing the zip trick of section for creating dictionaries finallywe use the translate method to do the actual substituting partition the partition method is similar to the list split method the difference is illustrated below' partition'' split'(' ''' '[' '' the difference is that the...
9,349
miscellaneous topics iii statements on the same line the same line you can write an if statement and the statement that goes with it on if == print'hello 'you can also combine several statements on line if you separate them by semicolons for examplea= = = don' overuse either of theseas they can make your code harder to...
9,350
you are usingand those machines may not have additional libraries you are using an option on windows is py exe this is third-party module that converts python programs to executables as of nowit is only available for python it can be little tricky to use here is script that you can use once you have py exe installed im...
9,351
miscellaneous topics iii
9,352
useful modules python comes with hundreds of modules that do all sorts of things there are also many thirdparty modules available for download from the internet this discusses few modules that have found useful importing modules there are couple of different ways to import modules here are several ways to import some f...
9,353
useful modules from itertools import combinations_with_replacement as cwr from math import log as ln location usuallyimport statements go at the beginning of the programbut there is no restriction they can go anywhere as long as they come before the code that uses the module getting help to get help on module (say the ...
9,354
dates the module datetime allows us to work with dates and times together the following line creates datetime object that contains the current date and timefrom datetime import datetime datetime( , , now(the datetime object has attributes yearmonthdayhourminutesecondand microsecond here is short exampled datetime( , , ...
9,355
useful modules : : am on february the leading zeros are little annoying you could combine strftime with the first way we learned to get nicer outputprint( strftime'{}% on % {'format( hour% day) am on february you can also create datetime object when doing soyou must specify the yearmonthand day the other attributes are...
9,356
directory here is an example that searches through all the files in directory and prints the names of those files that contain the word 'helloimport os directory ' :/users/heinold/desktopfiles os listdir(directoryfor in filesif os path isfile(directory+ ) open(directory+fread(if 'hello in sprint(fchanging and deleting ...
9,357
useful modules print(os path join'directory ''file txt ')(' :/users/heinold/desktop''file txt'file txt :/users/heinold/desktop directory\\file txt note that the standard separator in windows is the backslash the forward slash also works finallytwo other functions you might find helpful are the exists functionwhich test...
9,358
import zipfile zipfile zipfile'filename zip ' extractall' :/users/heinold/desktop/ getting files from the internet for getting files from the internet there is the urllib module here is simple examplefrom urllib request import urlopen page urlopen' page read(decode(the urlopen function returns an object that is lot lik...
9,359
useful modules your own modules creating your own modules is easy just write your python code and save it in file you can then import your module using the import statement
9,360
regular expressions the replace method of strings is used to replace all occurrences of one string with anotherand the index method is used to find the first occurrence of substring in string but sometimes you need to do more sophisticated search or replace for exampleyou may need to find all of the occurrences of stri...
9,361
regular expressions raw strings lot of the patterns use backslashes howeverbackslashes in strings are used for escape characterslike the newline\ to get backslash in stringwe need to do \this can quickly clutter up regular expression to avoid thisour patterns will be raw stringswhere backslashes can appear as is and do...
9,362
axxb the pattern matches an followed by almost any single character followed by exceptionthe one character not matched by the dot is the newline character if you need that to be matchedtooput ? at the start of your pattern matching multiple copies of something here is an example where we match an followed by one or mor...
9,363
regular expressions re sub( 'abc|xyz ''''abcdefxyz abc ''*def* *in the above exampleevery time we encounter an abc or an xyzwe replace it with an asterisk matching only at the start or end sometimes you don' want to match every occurrence of somethingmaybe just the first or the last occurrence to match just the first o...
9,364
re sub( '\ ''''this is test re sub( '\ ''''this is test or is it'or is it''this*is* *test **or*is*it?'*************preceding and following matches sometimes you want to match things if they are preceded or followed by something code description (?=matches only if followed by (?!matches only if not followed by (?<=match...
9,365
regular expressions (? -regular expressions can be long and complicated this flag allows you to use more verbosemulti-line formatwhere whitespace is ignored you can also put comments in here is an examplepattern """(? )[ab]\dmatch or followed by some digits [cd]\dmatch or followed by some digits ""print(re sub(pattern'...
9,366
here are some short examplesexpression description 'abcthe exact string abc '[abc]an abor '[ -za- ][ - ]match letter followed by digit '[ ] followed by any two characters (except newlines' +one or more ' ' *' ?any number of 'seven none zero or one ' { }exactly two ' ' { , }twothreeor four ' ' +?one or more ' taking as ...
9,367
regular expressions groups using parentheses around part of an expression creates group that contains the text that matches pattern you can use this to do more sophisticated substitutions here is an example that converts to lowercase every capital letter that is followed by lowercase letterdef modify(match)letters matc...
9,368
findall -the findall function returns list of all the matches found here is an examplere findall( '[ab]\ '' '[' '' '' 'as another exampleto find all the words in stringyou can do the followingre findall( '\ 'sthis is better than using split(because split does not handle punctuationwhile the regular expression does spli...
9,369
regular expressions finditer -this returns an iterator of match objects that we can loop throughlike belowfor in re finditer( '([ab])(\ '' + ')print( group( ) note that this is little more general than the findall function in that findall returns the matching stringswhereas finditer returns something like list of match...
9,370
if !=none and !''if in 'cm ''cd ''xc ''xl ''ix ''iv ']sum+= [xelif [ in 'mdclxvi 'sum+= [ [ ]]*len(xprint(sumenter roman numeralmcmxvii the regular expression itself is fairly straightforward it looks for up to three 'sfollowed by zero or one cm'sfollowed by zero or one cd'setc and stores each of those in group the for...
9,371
regular expressions the rest of the expression,?\ *(\ { })finds the year then we use the results to create the abbreviated date the only tricky part here is the first partwhich takes the month namechanges it to all lowercaseand takes only the first three characters and uses those as keys to dictionary this wayas long a...
9,372
math this is collection of topics that are at somewhat mathematical in naturethough many of them are of general interest the math module as mentioned in section the math module contains some common math functions here are most of themfunction description sincostan trig functions asinacosatan inverse trig functions atan...
9,373
math note note that the floor and int functions behave the same for positive numbersbut differently for negative numbers for instancefloor( and int( both return the integer howeverfloor(- returns - the greatest integer less than or equal to - while int(- returns - which is obtained by throwing away the decimal part of ...
9,374
comparing floating point numbers in section we saw that some numberslike are not represented exactly on computer mathematicallyafter the code below executesx should be but because of accumulated errorsit is actually for in range( ) + this means that the following if statement will turn out falseif == more reliable way ...
9,375
math converting to and from floats belowto convert fraction to floating point numberuse floatlike float(fraction( ) on the other handsay we want to convert to fraction unfortunatelywe should not do fraction becauseas mentionedsome numbersincluding are not represented exactly on the computer in factfraction returns the ...
9,376
how to get an exact decimal representation of from decimal import decimal decimal 'decimal(' 'the string here is important if we leave it outwe get decimal that corresponds with the inexact floating point representation of decimal decimal(' 'math you can use the usual math operators to work with decimal objects for exa...
9,377
math there is theoretically no limit to the precision you can usebut the higher the precisionthe more memory is required and the slower things will run in generaleven with small precisionsdecimal objects are slower than floating point numbers ordinary floating point arithmetic is enough for most problemsbut it is nice ...
9,378
xtrans= ytrans= xzoom= yzoom=- root tk(canvas canvas(width= height= canvas grid(image=image new(mode'rgb ',size=( , )draw imagedraw draw(imagefor in range( )c_x ( - )/float(xzoom)+xtrans for in range( ) complex(c_x( - )/float(yzoom)+ytranscount= = while abs( )< and count<max_iterz * + count + draw point(( , )fill=color...
9,379
math more with lists and arrays sparse lists , , , , list of integers requires several hundred terabytes of storagefar more than most hard drives can store howeverin many practical applicationsmost of the entries of list are this allows us to save lot of memory by just storing the nonzero values along with their locati...
9,380
that it uses mathematical process to generate random numbers the numbers are called pseudorandom numbers becausecoming from mathematical processthey are not truly randomthoughfor all intents and purposesthey appear random anyone who knows the process can recreate the numbers this is good for scientific and mathematical...
9,381
math there are bunch of other distributions that you can use the most common is the uniform distributionin which all values in range are equally likely for instancerandom uniform( , see the python documentation [ for information on the other distributions more random randint function one way to generate cryptographical...
9,382
' ' hexadecimal values are prefaced with xoctal values are prefaced with and binary values are prefaced with the int function the int function has an optional second argument that allows you to specify the base you are converting from here are few examplesint' ' int' ' int' ' int' ' convert from base convert from base ...
9,383
math logarithms use the natural logarithm lotand it is more natural for me to type ln instead of log if you want to do thatjust do the followingln log summing series here is way to get an approximate sum of seriesin this case = - sum([ /( ** - for in range( , )] another examplesay you need the sine of each of the angle...
9,384
working with functions this covers number of topics to do with functionsincluding some topics in functional programming first-class functions python functions are said to be first-class functionswhich means they can be assigned to variablescopiedused as arguments to other functionsetc just like any other object copying...
9,385
working with functions here is another example say you have program with ten different functions and the program has to decide at runtime which function to use one solution is to use ten if statements shorter solution is to use list of functions the example below assumes that we have already created functions that each...
9,386
sort(key=lambda xx[ ]the lambda keyword indicates that what follows will be an anonymous function we then have the arguments to the functionfollowed by colon and then the function code the function code cannot be longer than one line we used anonymous functions back when working with guis to pass information about whic...
9,387
working with functions mapfilterreduceand list comprehensions map and filter python has built-in functions called map and filter that are used to apply functions to the contents of list they date back to before list comprehensions were part of pythonbut now list comprehensions can accomplish everything these functions ...
9,388
def fact( )return reduce(lambda , : *yrange( , + ) the operator module in the previous sectionwhen we needed function to represent python operator like addition or multiplicationwe used an anonymous functionlike belowtotal reduce(lambda ,yx+yrange( , )python has module called operator that contains functions that accom...
9,389
working with functions ** ** you can also use these notations together with ordinary arguments the order matters--arguments collected by have to come after all positional arguments and arguments collected by *always come last two example function declarations are shown belowdef func(abc= * ** )def func(ab*cd= ** )calli...
9,390
the itertools and collections modules the itertools and collections modules contain functions that can greatly simplify some common programming tasks we will start with some functions in itertools permutations and combinations permutations the permutations of sequence are rearrangements of the items of that sequence fo...
9,391
the itertools and collections modules combinations if we want all the possible -element subsets from sequencewhere all that matters is the elementsnot the order in which they appearthen what we want are combinations for instancethe -element subsets that can be made from { are { }{ and { we consider { and { as being the...
9,392
grouping things the groupby function is handy for grouping things it breaks list up into groups by tracing through the list and every time there is change in valuesa new group is created the groupby function returns ordered pairs that consist of list item and groupby iterator object that contains the group of items [ f...
9,393
the itertools and collections modules firstsuppose is list of zeros and onesand we want to find out how long the longest run of ones is we can do that in one line using groupbymax([len(list(group)for key,group in groupby(lif key== ]secondsuppose we have function called easter that returns the date of easter in given ye...
9,394
counting things the collections module has useful class called counter you feed it an iterable and the counter object that is created is something very much like dictionary whose keys are items from the sequence and whose values are the number of occurrences of the keys in factcounter is subclass of dictpython' diction...
9,395
the itertools and collections modules from collections import counter import re open'filename txtread(words re findall'\ ' lower() counter(wordsto print the ten most common wordswe can do the followingfor wordfreq in most_common( )print(word''freqto pick out only those words that occur more than five timeswe can do the...
9,396
if we had tried this with dd just regular dictionarywe would have gotten an error the first time the program reached dd[ ]+= because dd[cdid not yet exist but since we declared dd to be defaultdict(int)each value is automatically assigned value of upon creationand so we avoid the error note that we could use regular di...
9,397
the itertools and collections modules
9,398
exceptions this provides brief introduction to exceptions basics if you are writing program that someone else is going to useyou don' want it to crash if an error occurs say your program is doing bunch of calculationsand at some point you have the line = / if ever happens to be you will get division by zero error and t...
9,399
exceptions hi there different possibilities we can have multiple statements in the try block and also and multiple except blockslike belowtrya eval(input'enter number')print ( /aexcept nameerrorprint'please enter number 'except zerodivisionerrorprint("can ' enter "not specifying the exception you can leave off the name...