id
int64
0
25.6k
text
stringlengths
0
4.59k
4,900
""import ossysfind heregets tools find count for filename in find find('pyc'sys argv[ ])count + print(filenameos remove(filenameprint('removed % pyc filescountwhen runall bytecode files in the tree rooted at the passed-in directory name are removed as beforethis timethoughour script works just about everywhere python doesc:\pp \toolscleanpyc-find-py py \find pyc \visitor pyc \__init__ pyc removed pyc files this works portablyand it avoids external program startup costs but find is really just half the story--it collects files matching name pattern but doesn' search their content although extra code can add such searching to find' resulta more manual approach can allow us to tap into the search process more directly the next section shows how python tree searcher after experimenting with greps and globs and findsin the endto help ease the task of performing global searches on all platforms might ever usei wound up coding task-specific python script to do most of the work for me example - employs the following standard python tools that we met in the preceding os walk to visit files in directoryos path splitext to skip over files with binary-type extensionsand os path join to portably combine directory path and filename because it' pure python codeit can be run the same way on both linux and windows in factit should work on any computer where python has been installed moreoverbecause it uses direct system callsit will likely be faster than approaches that rely on underlying shell commands example - pp \tools\search_all py ""###############################################################################use"python \tools\search_all py dir stringsearch all files at and below named directory for stringuses the os walk interfacerather than doing find find to collect names firstsimilar to calling visitfile for each find find result for "*patternsearching directory trees
4,901
""import ossys listonly false textexts [py'pyw'txt' ' 'ignore binary files def searcher(startdirsearchkey)global fcountvcount fcount vcount for (thisdirdirsherefilesherein os walk(startdir)for fname in filesheredo non-dir files here fpath os path join(thisdirfnamefnames have no dirpath visitfile(fpathsearchkeydef visitfile(fpathsearchkey)for each non-dir file global fcountvcount search for string print(vcount+ '=>'fpathskip protected files tryif not listonlyif os path splitext(fpath)[ not in textextsprint('skipping'fpathelif searchkey in open(fpathread()input('% has % (fpathsearchkey)fcount + exceptprint('failed:'fpathsys exc_info()[ ]vcount + if __name__ ='__main__'searcher(sys argv[ ]sys argv[ ]print('found in % filesvisited % (fcountvcount)operationallythis script works roughly the same as calling its visitfile function for every result generated by our find find tool with pattern of "*"but because this version is specific to searching content it can better tailored for its goal reallythis equivalence holds only because "*pattern invokes an exhaustive traversal in find findand that' all that this new script' searcher function does the finder is good at selecting specific file typesbut this script benefits from more custom single traversal when run standalonethe search key is passed on the command linewhen importedclients call this module' searcher function directly for exampleto search (that isgrepfor all appearances of string in the book examples treei run command line like this in dos or unix shellc:\\pp etools\search_all py mimetypes =\launchbrowser py =\launcher py =\launch_pydemos pyw =\launch_pygadgets_bar pyw =\__init__ py =\__init__ pyc complete system programs
4,902
=\preview\attachgui py =\preview\bob pkl skipping \preview\bob pkl more lines omittedpauses for enter key press at matches found in filesvisited the script lists each file it checks as it goestells you which files it is skipping (names that end in extensions not listed in the variable textexts that imply binary data)and pauses for an enter key press each time it announces file containing the search string the search_all script works the same way when it is imported rather than runbut there is no final statistics output line (fcount and vcount live in the module and so would have to be imported to be inspected here) :\pp \dev\examples\pp epython import tools search_all search_all searcher( ' :\temp\pp \examples''mimetypes'more lines omitted pauses for enter key press along the way search_all fcountsearch_all vcount matchesfiles ( however launchedthis script tracks down all references to string in an entire directory treea name of changed book examples fileobjector directoryfor instance it' exactly what was looking for--or at least thought sountil further deliberation drove me to seek more complete and better structured solutionsthe topic of the next section be sure to also see the coverage of regular expressions in the search_all script here searches for simple string in each file with the in string membership expressionbut it would be trivial to extend it to search for regular expression pattern match instead (roughlyjust replace in with call to regular expression object' search methodof coursesuch mutation will be much more trivial after we've learned how also notice the textexts list in example - which attempts to list all possible binary file typesit would be more general and robust to use the mimetypes logic we will meet near the end of this in order to guess file content type from its namebut the skips list provides more control and sufficed for the trees used this script against finally note that for simplicity many of the directory searches in this assume that text is encoded per the underlying platform' unicode default they could open text in binary mode to avoid decoding errorsbut searches might then be inaccurate because of encoding scheme differences in the raw encoded bytes to see how to do betterwatch for the "greputility in ' pyedit guiwhich will apply an encoding name to all the files in searched tree and ignore those text or binary files that fail to decode searching directory trees
4,903
laziness is the mother of many framework armed with the portable search_all script from example - was able to better pinpoint files to be edited every time changed the book examples tree content or structure at least initiallyin one window ran search_all to pick out suspicious files and edited each along the way by hand in another window pretty soonthoughthis became tedioustoo manually typing filenames into editor commands is no funespecially when the number of files to edit is large since occasionally have better things to do than manually start dozens of text editor sessionsi started looking for way to automatically run an editor on each suspicious file unfortunatelysearch_all simply prints results to the screen although that text could be intercepted with os popen and parsed by another programa more direct approach that spawns edit sessions during the search may be simpler that would require major changes to the tree search script as currently codedthoughand make it useful for just one specific purpose at this pointthree thoughts came to mindredundancy after writing few directory walking utilitiesit became clear that was rewriting the same sort of code over and over again traversals could be even further simplified by wrapping common details for reuse although the os walk tool avoids having to write recursive functionsits model tends to foster redundant operations and code ( directory name joinstracing printsextensibility past experience informed me that it would be better in the long run to add features to general directory searcher as external componentsrather than changing the original script itself because editing files was just one possible extension (what about automating text replacementstoo?) more generalcustomizableand reusable approach seemed the way to go although os walk is straightforward to useits nested loop-based structure doesn' quite lend itself to customization the way class can encapsulation based on past experiencei also knew that it' generally good idea to insulate programs from implementation details as much as possible while os walk hides the details of recursive traversalit still imposes very specific interface on its clientswhich is prone to change over time indeed it has--as 'll explain further at the end of this sectionone of python' tree walkers was removed altogether in xinstantly breaking code that relied upon it it would be better to hide such dependencies behind more neutral interfaceso that clients won' break as our needs change of courseif you've studied python in any depthyou know that all these goals point to using an object-oriented framework for traversals and searching example - is complete system programs
4,904
just wraps os walk for easier use and extensionas well as generic searchvisitor class that generalizes the notion of directory searches by itselfsearchvisitor simply does what search_all didbut it also opens up the search process to customization--bits of its behavior can be modified by overloading its methods in subclasses moreoverits core search logic can be reused everywhere we need to search simply define subclass that adds extensions for specific task the same goes for filevisitor--by redefining its methods and using its attributeswe can tap into tree search using oop coding techniques as is usual in programmingonce you repeat tactical tasks often enoughthey tend to inspire this kind of strategic thinking example - pp \tools\visitor py ""###################################################################################test"python \tools\visitor py dir testmask [string]uses classes and subclasses to wrap some of the details of os walk call usage to walk and searchtestmask is an integer bitmask with bit per available self-testsee alsovisitor_*py subclasses use casesframeworks should generally use__x pseudo private namesbut all names here are exported for use in subclasses and clientsredefine reset to support multiple independent walks that require subclass updates###################################################################################""import ossys class filevisitor""visits all nondirectory files below startdir (default ')override visitmethods to provide custom file/dir handlerscontext arg/attribute is optional subclass-specific statetrace switch is silent is directories adds files ""def __init__(selfcontext=nonetrace= )self fcount self dcount self context context self trace trace def run(selfstartdir=os curdirreset=true)if resetself reset(for (thisdirdirsherefilesherein os walk(startdir)self visitdir(thisdirfor fname in filesherefor non-dir files fpath os path join(thisdirfnamefnames have no path self visitfile(fpathdef reset(self)self fcount self dcount to reuse walker for independent walks def visitdir(selfdirpath)called for each dir visitorwalking directories "++
4,905
if self trace print(dirpath'override or extend me def visitfile(selffilepath)called for each file self fcount + override or extend me if self trace print(self fcount'=>'filepathclass searchvisitor(filevisitor)""search files at and below startdir for stringsubclassredefine visitmatchextension listscandidate as neededsubclasses can use testexts to specify file types to search (but can also redefine candidate to use mimetypes for text contentsee ahead""skipexts [testexts [txt'py'pyw'html' ' '#skipexts [gif'jpg'pyc' ' 'exe'search these exts or skip these exts def __init__(selfsearchkeytrace= )filevisitor __init__(selfsearchkeytraceself scount def reset(self)self scount on independent walks def candidate(selffname)ext os path splitext(fname)[ if self testextsreturn ext in self testexts elsereturn ext not in self skipexts redef for mimetypes def visitfile(selffname)filevisitor visitfile(selffnameif not self candidate(fname)if self trace print('skipping'fnameelsetext open(fnameread(if self context in textself visitmatch(fnametextself scount + test for match def visitmatch(selffnametext)print('% has % (fnameself context)process match override me lower if __name__ ='__main__'self-test logic dolist dosearch =do list and search donext when next test added def selftest(testmask) complete system programs in test list or not in skip list 'rbif undecodable or text find(!-
4,906
visitor filevisitor(trace= visitor run(sys argv[ ]print('visited % files and % dirs(visitor fcountvisitor dcount)if testmask dosearchvisitor searchvisitor(sys argv[ ]trace= visitor run(sys argv[ ]print('found in % filesvisited % (visitor scountvisitor fcount)selftest(int(sys argv[ ]) dolist dosearch this module primarily serves to export classes for external usebut it does something useful when run standalonetoo if you invoke it as script with test mask of and root directory nameit makes and runs filevisitor object and prints an exhaustive listing of every file and directory at and below the rootc:\pp \toolsvisitor py :\temp\pp \examples :\temp\pp \examples = :\temp\pp \examples\readme-root txt :\temp\pp \examples\pp = :\temp\pp \examples\pp \echoenvironment pyw = :\temp\pp \examples\pp \launchbrowser pyw = :\temp\pp \examples\pp \launcher py = :\temp\pp \examples\pp \launcher pyc more output omitted (pipe into more or file = :\temp\pp \examples\pp \system\threads\thread-count py = :\temp\pp \examples\pp \system\threads\thread py :\temp\pp \examples\pp \tempparts = :\temp\pp \examples\pp \tempparts\ jpg = :\temp\pp \examples\pp \tempparts\lawnlake -jan- jpg = :\temp\pp \examples\pp \tempparts\part- txt = :\temp\pp \examples\pp \tempparts\part- html visited files and dirs if you instead invoke this script with as its first command-line argumentit makes and runs searchvisitor object using the third argument as the search key this form is similar to running the search_all py script we met earlierbut it simply reports each matching file without pausingc:\pp \toolsvisitor py :\temp\pp \examples mimetypes :\temp\pp \examples\pp \extras\losalamosadvancedclass\day -system\data txt ha mimetypes :\temp\pp \examples\pp \internet\email\mailtools\mailparser py has mimetypes :\temp\pp \examples\pp \internet\email\mailtools\mailsender py has mimetypes :\temp\pp \examples\pp \internet\ftp\mirror\downloadflat py has mimetypes :\temp\pp \examples\pp \internet\ftp\mirror\downloadflat_modular py has mimet ypes :\temp\pp \examples\pp \internet\ftp\mirror\ftptools py has mimetypes :\temp\pp \examples\pp \internet\ftp\mirror\uploadflat py has mimetypes :\temp\pp \examples\pp \system\media\playfile py has mimetypes found in filesvisited visitorwalking directories "++
4,907
searchvisitor (two separate traversals are performedthe first argument is really used as bit mask to select one or more supported self-testsif test' bit is on in the binary value of the argumentthe test will be run because is in binaryit selects both search ( and listing ( in more user-friendly systemwe might want to be more symbolic about that ( check for -search and -list arguments)but bit masks work just as well for this script' scope as usualthis module can also be used interactively the following is one way to determine how many files and directories you have in specific directoriesthe last command walks over your entire drive (after generally noticeable delay!see also the "biggest fileexample at the start of this for issues such as potential repeat visits not handled by this walkerc:\pp \toolspython from visitor import filevisitor filevisitor(trace= run( ' :\temp\pp \examples' dcountv fcount ( run(' dcountv fcount ( independent walk (reset countsv run('reset=falsev dcountv fcount ( accumulative walk (keep countsv filevisitor(trace= run( ' :\\' dcountv fcount ( new independent walker (own countsentire drivetry '/on unix-en although the visitor module is useful by itself for listing and searching treesit was really designed to be extended in the rest of this sectionlet' quickly step through handful of visitor clients which add more specific tree operationsusing normal oo customization techniques editing files in directory trees (visitorafter genericizing tree traversals and searchesit' easy to add automatic file editing in brand-newseparate component example - defines new editvisitor class that simply customizes the visitmatch method of the searchvisitor class to open text editor on the matched file yesthis is the complete program--it needs to do something special only when visiting matched filesand so it needs to provide only that behavior the rest of the traversal and search logic is unchanged and inherited complete system programs
4,908
""use"python \tools\visitor_edit py string rootdir?add auto-editor startup to searchvisitor in an external subclass componentautomatically pops up an editor on each file containing string as it traversescan also use editor='editor 'notepadon windowsto use texteditor from later in the booktry 'python gui\texteditor\texteditor py'could also send search command to go to the first match on start in some editors""import ossys from visitor import searchvisitor class editvisitor(searchvisitor)""edit files at and below startdir having string ""editor ' :\cygwin\bin\vim-nox exeymmvdef visitmatch(selffpathnametext)os system('% % (self editorfpathname)if __name__ ='__main__'visitor editvisitor(sys argv[ ]visitor run(if len(sys argv else sys argv[ ]print('edited % filesvisited % (visitor scountvisitor fcount)when we make and run an editvisitora text editor is started with the os system command-line spawn callwhich usually blocks its caller until the spawned program finishes as codedwhen run on my machineseach time this script finds matched file during the traversalit starts up the vi text editor within the console window where the script was startedexiting the editor resumes the tree walk let' find and edit some files when run as scriptwe pass this program the search string as command argument (herethe string mimetypes is the search keythe root directory passed to the run method is either the second argument or (the current run directoryby default traversal status messages show up in the consolebut each matched file now automatically pops up in text editor along the way in the followingthe editor is started eight times--try this with an editor and tree of your own to get better feel for how it worksc:\pp \toolsvisitor_edit py mimetypes :\temp\pp \examples :\temp\pp \examples = :\temp\pp \examples\readme-root txt :\temp\pp \examples\pp = :\temp\pp \examples\pp \echoenvironment pyw = :\temp\pp \examples\pp \launchbrowser pyw = :\temp\pp \examples\pp \launcher py = :\temp\pp \examples\pp \launcher pyc skipping :\temp\pp \examples\pp \launcher pyc more output omitted = :\temp\pp \examples\pp \tempparts\lawnlake -jan- jpg visitorwalking directories "++
4,909
= :\temp\pp \examples\pp \tempparts\part- txt = :\temp\pp \examples\pp \tempparts\part- html edited filesvisited thisfinallyis the exact tool was looking for to simplify global book examples tree maintenance after major changes to things such as shared modules and file and directory namesi run this script on the examples root directory with an appropriate search string and edit any files it pops up as needed still need to change files by hand in the editorbut that' often safer than blind global replacements global replacements in directory trees (visitorbut since brought it upgiven general tree traversal classit' easy to code global search-and-replace subclasstoo the replacevisitor class in example - is search visitor subclass that customizes the visitfile method to globally replace any appearances of one string with anotherin all text files at and below root directory it also collects the names of all files that were changed in list just in case you wish to go through and verify the automatic edits applied ( text editor could be automatically popped up on each changed filefor instanceexample - pp \tools\visitor_replace py ""use"python \tools\visitor_replace py rootdir fromstr tostrdoes global search-and-replace in all files in directory treereplaces fromstr with tostr in all text filesthis is powerful but dangerous!visitor_edit py runs an editor for you to verify and make changesand so is saferuse visitor_collect py to simply collect matched files listlistonly mode here is similar to both searchvisitor and collectvisitor""import sys from visitor import searchvisitor class replacevisitor(searchvisitor)""change fromstr to tostr in files at and below startdirfiles changed available in obj changed list after run ""def __init__(selffromstrtostrlistonly=falsetrace= )self changed [self tostr tostr self listonly listonly searchvisitor __init__(selffromstrtracedef visitmatch(selffnametext)self changed append(fnameif not self listonlyfromstrtostr self contextself tostr text text replace(fromstrtostropen(fname' 'write(text complete system programs
4,910
listonly input('list only?'='yvisitor replacevisitor(sys argv[ ]sys argv[ ]listonlyif listonly or input('proceed with changes?'=' 'visitor run(startdir=sys argv[ ]action 'changedif not listonly else 'foundprint('visited % filesvisitor fcountprint(action'% files:len(visitor changed)for fname in visitor changedprint(fnameto run this script over directory treerun the following sort of command line with appropriate "fromand "tostrings on my shockingly underpowered netbook machinedoing this on -file tree and changing files along the way takes roughly three seconds of real clock time when the system isn' particularly busy :\pp \toolsvisitor_replace py :\temp\pp \examples pp pp list only? visited files found filesc:\temp\pp \examples\readme-root txt :\temp\pp \examples\pp \echoenvironment pyw :\temp\pp \examples\pp \launcher py more matching filenames omitted :\pp \toolsvisitor_replace py :\temp\pp \examples pp pp list only? proceed with changes? visited files changed filesc:\temp\pp \examples\readme-root txt :\temp\pp \examples\pp \echoenvironment pyw :\temp\pp \examples\pp \launcher py more changed filenames omitted :\pp \toolsvisitor_replace py :\temp\pp \examples pp pp list only? proceed with changes? visited files changed filesnaturallywe can also check our work by running the visitor script (and searchvisitor superclass) :\pp \toolsvisitor py :\temp\pp \examples pp found in filesvisited :\pp \toolsvisitor py :\temp\pp \examples pp :\temp\pp \examples\readme-root txt has pp :\temp\pp \examples\pp \echoenvironment pyw has pp :\temp\pp \examples\pp \launcher py has pp more matching filenames omitted found in filesvisited visitorwalking directories "++
4,911
in places you didn' anticipateyou might just ruin an entire tree of files by running the replacevisitor object defined here on the other handif the string is something very specificthis object can obviate the need to manually edit suspicious files for instancewebsite addresses in html files are likely too specific to show up in other places by chance counting source code lines (visitorthe two preceding visitor module clients were both search-orientedbut it' just as easy to extend the basic walker class for more specific goals example - for instanceextends filevisitor to count the number of lines in program source code files of various types throughout an entire tree the effect is much like calling the visitfile method of this class for each filename returned by the find tool we wrote earlier in this but the oo structure here is arguably more flexible and extensible example - pp \tools\visitor_sloc py ""count lines among all program source files in tree named on the command lineand report totals grouped by file types (extensiona simple sloc (source lines of codemetricskip blank and comment lines if desired ""import syspprintos from visitor import filevisitor class linesbytype(filevisitor)srcexts [define in subclass def __init__(selftrace= )filevisitor __init__(selftrace=traceself srclines self srcfiles self extsums {extdict(files= lines= for ext in self srcextsdef visitsource(selffpathext)if self trace print(os path basename(fpath)lines len(open(fpath'rb'readlines()self srcfiles + self srclines +lines self extsums[ext]['files'+ self extsums[ext]['lines'+lines def visitfile(selffilepath)filevisitor visitfile(selffilepathfor ext in self srcextsif filepath endswith(ext)self visitsource(filepathextbreak class pylines(linesbytype)srcexts [py'pyw'just python files complete system programs
4,912
srcexts [py'pyw'cgi'html' 'cxx' ' 'if __name__ ='__main__'walker sourcelines(walker run(sys argv[ ]print('visited % files and % dirs(walker fcountwalker dcount)print('-'* print('source files=>%dlines=>% (walker srcfileswalker srclines)print('by types:'pprint pprint(walker extsumsprint('\ncheck sums:'end='print(sum( ['lines'for in walker extsums values())end='print(sum( ['files'for in walker extsums values())print('\npython only walk:'walker pylines(trace= walker run(sys argv[ ]pprint pprint(walker extsumswhen run as scriptwe get trace messages during the walk (omitted here to save space)and report with line counts grouped by file type run this on trees of your own to watch its progressmy tree has source files and source linesincluding files and lines of pypython codec:\pp \toolsvisitor_sloc py :\temp\pp \examples visited files and dirs source files=> lines=> by types{ '{'files' 'lines' }cgi'{'files' 'lines' }cxx'{'files' 'lines' } '{'files' 'lines' }html'{'files' 'lines' } '{'files' 'lines' }py'{'files' 'lines' }pyw'{'files' 'lines' }check sums python only walk{py'{'files' 'lines' }pyw'{'files' 'lines' }recoding copies with classes (visitorlet' peek at one more visitor use case when first wrote the cpall py script earlier in this couldn' see way that the visitor class hierarchy we met earlier would help two directories needed to be traversed in parallel (the original and the copy)and visitor is based on walking just one tree with os walk there seemed no easy way to keep track of where the script was in the copy directory visitorwalking directories "++
4,913
example - simply replaces the "fromdirectory path string with the "todirectory path stringat the front of all directory names and pathnames passed in from os walk the results of the string replacements are the paths to which the original files and directories are to be copied example - pp \tools\visitor_cpall py ""use"python \tools\visitor_cpall py fromdir todir trace?like system\filetools\cpall pybut with the visitor classes and os walkdoes string replacement of fromdir with todir at the front of all the names that the walker passes inassumes that the todir does not exist initially""import os from visitor import filevisitor from pp system filetools cpall import copyfile visitor is in pp is in dir on path class cpallvisitor(filevisitor)def __init__(selffromdirtodirtrace=true)self fromdirlen len(fromdir self todir todir filevisitor __init__(selftrace=tracedef visitdir(selfdirpath)topath os path join(self todirdirpath[self fromdirlen:]if self traceprint(' 'dirpath'=>'topathos mkdir(topathself dcount + def visitfile(selffilepath)topath os path join(self todirfilepath[self fromdirlen:]if self traceprint(' 'filepath'=>'topathcopyfile(filepathtopathself fcount + if __name__ ='__main__'import systime fromdirtodir sys argv[ : trace len(sys argv print('copying 'start time clock(walker cpallvisitor(fromdirtodirtracewalker run(startdir=fromdirprint('copied'walker fcount'files,'walker dcount'directories'end='print('in'time clock(start'seconds' complete system programs
4,914
assumptions to keep the code simple the "todirectory is assumed not to exist initiallyand exceptions are not ignored along the way here it is copying the book examples tree from the prior edition again on windowsc:\pp \toolsset pythonpath pythonpath= :\users\mark\stuff\books\ \pp \dev\examples :\pp \toolsrmdir / copytemp copytempare you sure ( / ) :\pp \toolsvisitor_cpall py :\temp\pp \examples copytemp copying copied files directories in seconds :\pp \toolsfc / copytemp\pp \launcher py :\temp\pp \examples\pp \launcher py comparing files copytemp\pp \launcher py and :\temp\pp \examples\pp \launcher py fcno differences encountered despite the extra string slicing going onthis version seems to run just as fast as the original (the actual difference can be chalked up to system load variationsfor tracing purposesthis version also prints all the "fromand "tocopy paths during the traversal if you pass in third argument on the command linec:\pp \toolsrmdir / copytemp copytempare you sure ( / ) :\pp \toolsvisitor_cpall py :\temp\pp \examples copytemp copying :\temp\pp \examples =copytempf :\temp\pp \examples\readme-root txt =copytemp\readme-root txt :\temp\pp \examples\pp =copytemp\pp more lines omittedtry this on your own for the full output other visitor examples (externalalthough the visitor is widely applicablewe don' have space to explore additional subclasses in this book for more example clients and use casessee the following examples in book' examples distribution package described in the prefacetools\visitor_collect py collects and/or prints files containing search string tools\visitor_poundbang py replaces directory paths in "#!lines at the top of unix scripts tools\visitor_cleanpyc py is visitor-based recoding of our earlier bytecode cleanup scripts tools\visitor_bigpy py is visitor-based version of the "biggest fileexample at the start of this visitorwalking directories "++
4,915
the visitor framework handles walking details automatically the collectorfor instancesimply appends to list as search visitor detects matched files and allows the default list of text filename extensions in the search visitor to be overridden per instance--it' roughly like combination of find and grep on unixfrom visitor_collect import collectvisitor collectvisitor('mimetypes'testexts=[py'pyw']trace= run( ' :\temp\pp \examples'for name in matchesprint(namepy and pyw files with 'mimetypesc:\temp\pp \examples\pp \internet\email\mailtools\mailparser py :\temp\pp \examples\pp \internet\email\mailtools\mailsender py :\temp\pp \examples\pp \internet\ftp\mirror\downloadflat py :\temp\pp \examples\pp \internet\ftp\mirror\downloadflat_modular py :\temp\pp \examples\pp \internet\ftp\mirror\ftptools py :\temp\pp \examples\pp \internet\ftp\mirror\uploadflat py :\temp\pp \examples\pp \system\media\playfile py :\pp \toolsvisitor_collect py mimetypes :\temp\pp \examples as script the core logic of the biggest-file visitor is similarly straightforwardand harkens back to startclass bigpy(filevisitor)def __init__(selftrace= )filevisitor __init__(selfcontext=[]trace=tracedef visitfile(selffilepath)filevisitor visitfile(selffilepathif filepath endswith(py')self context append((os path getsize(filepath)filepath)and the bytecode-removal visitor brings us back full circleshowing an additional alternative to those we met earlier in this it' essentially the same codebut it runs os remove on pycfile visits in the endwhile the visitor classes are really just simple wrappers for os walkthey further automate walking chores and provide general framework and alternative classbased structure which may seem more natural to some than simple unstructured loops they're also representative of how python' oop support maps well to real-world structures like file systems although os walk works well for one-off scriptsthe better extensibilityreduced redundancyand greater encapsulation possible with oop can be major asset in real work as our needs change and evolve over time complete system programs
4,916
fourth editions of this bookthe original os path walk call was removed in python xand os walk became the only automated way to perform tree walks in the standard library examples from the prior edition that used os path walk were effectively broken by contrastalthough the visitor classes used this calltooits clients did not because updating the visitor classes to use os walk internally did not alter those classesinterfacesvisitor-based tools continued to work unchanged this seems prime example of the benefits of oop' support for encapsulation although the future is never completely predictablein practiceuser-defined tools like visitor tend to give you more control over changes than standard library tools like os walk trust me on thatas someone who has had to update three python books over the last yearsi can say with some certainty that python change is constantplaying media files we have space for just one lastquick example in this so we'll close with bit of fun did you notice how the file extensions for text and binary file types were hardcoded in the directory search scripts of the prior two sectionsthat approach works for the trees they were applied tobut it' not necessarily complete or portable it would be better if we could deduce file type from file name automatically that' exactly what python' mimetypes module can do for us in this sectionwe'll use it to build script that attempts to launch file based upon its media typeand in the process develop general tools for opening media portably with specific or generic players as we've seenon windows this task is trivial--the os startfile call opens files per the windows registrya system-wide mapping of file extension types to handler programs on other platformswe can either run specific media handlers per media typeor fall back on resident web browser to open the file generically using python' webbrowser module example - puts these ideas into code example - pp \system\media\playfile py #!/usr/local/bin/python ""#################################################################################try to play an arbitrary media file allows for specific players instead of always using general web browser scheme may not work on your system as isaudio files use filters and command lines on unixand filename associations on windows via the start command ( whatever you have on your machine to run au files--an audio playeror perhaps web browserconfigure and extend as needed playknownfile assumes you know what sort of media you wish to openand playfile tries to determine media type automatically using python mimetypes moduleboth try to launch web browser with python webbrowser module as last resort when mimetype or platform unknown #################################################################################""playing media files
4,917
helpmsg ""sorrycan' find media player for '%son your systemadd an entry for your system to the media player dictionary for this type of file in playfile pyor play the file manually ""def trace(*args)print(*argswith spaces between #################################################################################player techniquesgeneric and otherwiseextend me #################################################################################class mediatooldef __init__(selfruntext='')self runtext runtext def run(selfmediafile**options)fullpath os path abspath(mediafileself open(fullpath**optionsmost ignore options cwd may be anything class filter(mediatool)def open(selfmediafile**ignored)media open(mediafile'rb'player os popen(self runtext' 'player write(media read()spawn shell tool send to its stdin class cmdline(mediatool)def open(selfmediafile**ignored)cmdline self runtext mediafile os system(cmdlinerun any cmd line use % for filename class winstart(mediatool)use windows registry def open(selfmediafilewait=false**other)or os system('start file'if not waitallow wait for curr media os startfile(mediafileelseos system('start /wait mediafileclass webbrowser(mediatool)file:/requires abs path def open(selfmediafile**options)webbrowser open_new('file://%smediafile**options#################################################################################mediaand platform-specific policieschange meor pass one in #################################################################################map platform to playerchange meaudiotools 'sunos 'filter('/usr/bin/audioplay')'linux 'cmdline('cat % /dev/audio')'sunos 'filter('/usr/demo/sound/play') complete system programs os popen(write(on zaurusat least yesthis is that old
4,918
#'win 'winstart(cmdline('start % 'videotools 'linux 'cmdline('tkcvideo_c % ')'win 'winstart()imagetools 'linux 'cmdline('zimager % ')'win 'winstart()texttools 'linux 'cmdline('vi % ')'win 'cmdline('notepad % 'apptools 'win 'winstart(startfile or system zaurus pda avoid dos pop up zaurus pda zaurus pda or try pyeditdocxlsetcuse at your own riskmap mimetype of filenames to player tables mimetable {'audio'audiotools'video'videotools'image'imagetools'text'texttools'application'apptoolsnot html textbrowser #################################################################################top-level interfaces #################################################################################def trywebbrowser(filenamehelpmsg=helpmsg**options)""try to open file in web browser last resort if unknown mimetype or platformand for text/html ""trace('trying browser'filenametryplayer webbrowser(open in local browser player run(filename**optionsexceptprint(helpmsg filenameelse nothing worked def playknownfile(filenameplayertable={}**options)""play media file of known typeuses platform-specific player objectsor spawns web browser if nothing for this platformaccepts media-specific player table ""if sys platform in playertableplayertable[sys platformrun(filename**optionsspecific tool playing media files
4,919
trywebbrowser(filename**optionsgeneral scheme def playfile(filenamemimetable=mimetable**options)""play media file of any typeuses mimetypes to guess media type and map to platform-specific player tablesspawn web browser if text/htmlmedia type unknownor has no table ""contenttypeencoding mimetypes guess_type(filenameif contenttype =none or encoding is not nonecontenttype '?/?maintypesubtype contenttype split('/' if maintype ='textand subtype ='html'trywebbrowser(filename**optionselif maintype in mimetableplayknownfile(filenamemimetable[maintype]**optionselsetrywebbrowser(filename**optionscheck name can' guess poss txt gz 'image/jpegspecial case try table other types ##############################################################################self-test code ##############################################################################if __name__ ='__main__'media type known playknownfile('sousa au'audiotoolswait=trueplayknownfile('ora-pp gif'imagetoolswait=trueplayknownfile('ora-lp jpg'imagetoolsmedia type guessed input('stop players and press enter'playfile('ora-lp jpg'playfile('ora-pp gif'playfile('priorcalendar html'playfile('lp -preface-preview html'playfile('lp-code-readme txt'playfile('spam doc'playfile('spreadsheet xls'playfile('sousa au'wait=trueinput('done'image/jpeg image/gif text/html text/html text/plain app app audio/basic stay open if clicked although it' generally possible to open most media files by passing their names to web browser these daysthis module provides simple framework for launching media files with more specific toolstailored by both media type and platform web browser is used only as fallback optionif more specific tools are not available the net result is an extendable media file playerwhich is as specific and portable as the customizations you provide for its tables we've seen the program launch tools employed by this script in prior the script' main new concepts have to do with the modules it usesthe webbrowser module to open some files in local web browseras well as the python mimetypes module to complete system programs
4,920
let' explore these briefly before we run the script the python webbrowser module the standard library webbrowser module used by this example provides portable interface for launching web browsers from python scripts it attempts to locate suitable web browser on your local machine to open given url (file or web addressfor display its interface is straightforwardimport webbrowser webbrowser open_new('file://fullfilenameuse os path abspath(this code will open the named file in new web browser window using whatever browser is found on the underlying computeror raise an exception if it cannot you can tailor the browsers used on your platformand the order in which they are attemptedby using the browser environment variable and register function by defaultwebbrowser attempts to be automatically portable across platforms use an argument string of the form "file:/or "computer or web serverrespectively in factyou can pass in any url that the browser understands the following pops up python' home page in new locally-running browser windowfor examplewebbrowser open_new('among other thingsthis is an easy way to display html documents as well as media filesas demonstrated by this section' example for broader applicabilitythis module can be used as both command-line script (python' - module search path flag helps hereand as importable toolc:\users\mark\stuff\websites\public_htmlpython - webbrowser about-pp html :\users\mark\stuff\websites\public_htmlpython - webbrowser - about-pp html :\users\mark\stuff\websites\public_htmlpython - webbrowser - about-pp html :\users\mark\stuff\websites\public_htmlpython import webbrowser webbrowser open('about-pp html'reusenew windownew tab true webbrowser open_new('about-pp html'file:/optional on windows true webbrowser open_new_tab('about-pp html'true in both modesthe difference between the three usage forms is that the first tries to reuse an already-open browser window if possiblethe second tries to open new windowand the third tries to open new tab in practicethoughtheir behavior is totally dependent on what the browser selected on your platform supportsand even on the platform in general all three forms may behave the same playing media files
4,921
new tab in an existing window under internet explorer this is also why didn' need the "file://full url prefix in the preceding listing technicallyinternet explorer is only run if this is what is registered on your computer for the file type being openedif notthat file type' handler is opened instead some imagesfor examplemay open in photo viewer instead on other platformssuch as unix and mac os xbrowser behavior differsand non-url file names might not be openeduse "file://for portability we'll use this module again later in this book for examplethe pymailgui program in will employ it as way to display html-formatted email messages and attachmentsas well as program help see the python library manual for more details in and we'll also meet related callurllib request urlopenwhich fetches web page' text given urlbut does not open it in browserit may be parsedsavedor otherwise used the python mimetypes module to make this media player module even more usefulwe also use the python mimetypes standard library module to automatically determine the media type from the filename we get back type/subtype mime content-type string if the type can be determined or none if the guess failedimport mimetypes mimetypes guess_type('spam jpg'('image/jpeg'nonemimetypes guess_type('thebrightsideoflife mp '('audio/mpeg'nonemimetypes guess_type('lifeofbrian mpg'('video/mpeg'nonemimetypes guess_type('lifeofbrian xyz'(nonenoneunknown type stripping off the first part of the content-type string gives the file' general media typewhich we can use to select generic playerthe second part (subtypecan tell us if text is plain or htmlcontypeencoding mimetypes guess_type('spam jpg'contype split('/')[ 'imagemimetypes guess_type('spam txt'('text/plain'nonemimetypes guess_type('spam html'('text/html'none complete system programs subtype is 'plain
4,922
'htmla subtle thingthe second item in the tuple returned from the mimetypes guess is an encoding type we won' use here for opening purposes we still have to pay attention to itthough--if it is not noneit means the file is compressed (gzip or compress)even if we receive media content type for exampleif the filename is something like spam gif gzit' compressed image that we don' want to try to open directlymimetypes guess_type('spam gz'(none'gzip'content unknown mimetypes guess_type('spam gif gz'('image/gif''gzip'don' play memimetypes guess_type('spam zip'('application/zip'nonearchives mimetypes guess_type('spam doc'('application/msword'noneoffice app files if the filename you pass in contains directory paththe path portion is ignored (only the extension is usedthis module is even smart enough to give us filename extension for type--useful if we need to go the other wayand create file name from content typemimetypes guess_type( ' :\songs\sousa au'('audio/basic'nonemimetypes guess_extension('audio/basic'autry more calls on your own for more details we'll use the mimetypes module again in ftp examples in to determine transfer type (text or binary)and in our email examples in and to sendsaveand open mail attachments in example - we use mimetypes to select table of platform-specific player commands for the media type of the file to be played that iswe pick player table for the file' media typeand then pick command from the player table for the platform at both stepswe give up and run web browser if there is nothing more specific to be done using mimetypes guesses for searchvisitor to use this module for directing our text file search scripts we wrote earlier in this simply extract the first item in the content-type returned for file' name for instanceall in the following list are considered text (except pyw"which we may have to special-case if we must care)for ext in [txt'py'pyw'html' ' 'xml']print(extmimetypes guess_type('spamext)playing media files
4,923
py ('text/ -python'nonepyw (nonenonehtml ('text/html'nonec ('text/plain'noneh ('text/plain'nonexml ('text/xml'nonewe can add this technique to our earlier searchvisitor class by redefining its candidate selection methodin order to replace its default extension lists with mimetypes guesses-yet more evidence of the power of oop customization at workc:\pp \toolspython import mimetypes from visitor import searchvisitor or pp tools visitor if not class searchmimevisitor(searchvisitor)def candidate(selffname)contypeencoding mimetypes guess_type(fnamereturn (contype and contype split('/')[ ='textand encoding =nonev searchmimevisitor('mimetypes'trace= search key run( ' :\temp\pp \examples'root dir :\temp\pp \examples\pp \extras\losalamosadvancedclass\day -system\data txt ha mimetypes :\temp\pp \examples\pp \internet\email\mailtools\mailparser py has mimetypes :\temp\pp \examples\pp \internet\email\mailtools\mailsender py has mimetypes :\temp\pp \examples\pp \internet\ftp\mirror\downloadflat py has mimetypes :\temp\pp \examples\pp \internet\ftp\mirror\downloadflat_modular py has mimet ypes :\temp\pp \examples\pp \internet\ftp\mirror\ftptools py has mimetypes :\temp\pp \examples\pp \internet\ftp\mirror\uploadflat py has mimetypes :\temp\pp \examples\pp \system\media\playfile py has mimetypes scountv fcountv dcount ( because this is not completely accuratethough (you may need to add logic to include extensions like pywmissed by the guess)and because it' not even appropriate for all search clients (some may want to search specific kinds of text only)this scheme was not used for the original class using and tailoring it for your own searches is left as optional exercise running the script nowwhen example - is run from the command lineif all goes well its canned selftest code at the end opens number of audioimagetextand other file types located in the script' directoryusing either platform-specific players or general web browser on my windows laptopgif and html files open in new ie browser tabsjpeg files in windows photo viewerplain text files in notepaddoc and xls files in microsoft word and exceland audio files in windows media player complete system programs
4,924
computer and with your own test files to see what happens as usualyou can also test it interactively (use the package path like this one to import from different directoryassuming your module search path includes the pp root)from pp system media playfile import playfile playfile( ' :\movies\mov mpg'video/mpeg we'll use the playfile module again as an imported library like this in to open media files downloaded by ftp againyou may want to tweak this script' tables for your players this script also assumes the media file is located on the local machine (even though the webbrowser module supports remote files with "it does not currently allow different players for most different mime subtypes (it special-cases text to handle "plainand "htmldifferentlybut no othersin factthis script is really just something of simple framework that was designed to be extended as alwayshack onthis is pythonafter all automated program launchers (externalfinallysome optional reading--in the examples distribution package for this book (available at sites listed in the prefaceyou can find additional system-related scripts we do not have space to cover herepp \launcher py--contains tools used by some gui programs later in the book to start python programs without any environment configuration roughlyit sets up both the system path and module import search paths as needed to run book exampleswhich are inherited by spawned programs by using this module to search for files and configure environments automaticallyusers can avoid (or at least postponehaving to learn the intricacies of manual environment configuration before running programs though there is not much new in this example from system interfaces perspectivewe'll refer back to it laterwhen we explore gui programs that use its toolsas well as those of its launchmodes cousinwhich we wrote in pp \launch_pydemos pyw and pp \launch_pygadgets_bar pyw--use launcher py to start major gui book examples without any environment configuration because all spawned processes inherit configurations performed by the launcherthey all run with proper search path settings when run directlythe underlying pydemos pyw and pygadgets_bar pyw scripts (which we'll explore briefly at the end of instead rely on the configuration settings on the underlying machine in other wordslauncher effectively hides configuration details from the gui interfaces by enclosing them in configuration program layer pp \launchbrowser pyw--portably locates and starts an internet web browser program on the host machine in order to view local file or remote web page in automated program launchers (external
4,925
run the original version of this example has now been largely superseded by the standard library' webbrowser modulewhich arose after this example had been developed (reptilian minds think alike!in this editionlaunchbrowser simply parses command-line arguments for backward compatibility and invokes the open function in webbrowser see this module' help textor pygadgets and pydemos in for example command-line usage that' the end of our system tools exploration in the next part of this book we leave the realm of the system shell and move on to explore ways to add graphical user interfaces to our program laterwe'll do the same using web-based approaches as we continuekeep in mind that the system tools we've studied in this part of the book see action in wide variety of programs for instancewe'll put threads to work to spawn long-running tasks in the gui partuse both threads and processes when exploring server implementations in the internet partand use files and file-related system calls throughout the remainder of the book whether your interfaces are command linesmultiwindow guisor distributed clientserver websitespython' system interfaces toolbox is sure to play important part in your python programming future complete system programs
4,926
gui programming this part of the book shows you how to apply python to build portable graphical user interfacesprimarily with python' standard tkinter library the following cover this topic in depth this outlines gui options available to python developersand then presents brief tutorial that illustrates core tkinter coding concepts this begins two-part tour of the tkinter library--its widget set and related tools this first tour covers simpler library tools and widgetspop-up windowsvarious types of buttonsimagesand so on this continues the library tour begun in the prior it presents the rest of the tkinter widget libraryincluding menustextcanvasesscroll barsgridsand time-based events and animation this takes look at gui programming techniqueswe'll learn how to build menus automatically from object templatesspawn guis as separate programsrun long-running tasks in parallel with threads and queuesand more this pulls the earlier ideas together to implement collection of user interfaces it presents number of larger guis--clockstext editorsdrawing programsimage viewersand so on--which also demonstrate general python programming-in-the-large concepts along the way as in the first part of this bookthe material presented here is applicable to wide variety of domains and will be utilized again to build domain-specific user interfaces in later of this book for instancethe pymailgui and pycalc examples of later will assume that you've covered the basics here
4,927
graphical user interfaces "here' looking at youkidfor most software systemsa graphical user interface (guihas become an expected part of the package even if the gui acronym is new to youchances are that you are already familiar with such interfaces--the windowsbuttonsand menus that we use to interact with software programs in factmost of what we do on computers today is done with some sort of point-and-click graphical interface from web browsers to system toolsprograms are routinely dressed up with gui component to make them more flexible and easier to use in this part of the bookwe will learn how to make python scripts sprout such graphical interfacestooby studying examples of programming with the tkinter modulea portable gui library that is standard part of the python system and the toolkit most widely used by python programmers as we'll seeit' easy to program user interfaces in python scripts thanks to both the simplicity of the language and the power of its gui libraries as an added bonusguis programmed in python with tkinter are automatically portable to all major computer systems gui programming topics because guis are major areai want to say few more words about this part of the book before we get started to make them easier to absorbgui programming topics are split over the next five this begins with quick tkinter tutorial to teach coding basics interfaces are kept simple here on purposeso you can master the fundamentals before moving on to the following interfaces on the other handthis covers all the basicsevent processingthe pack geometry managerusing inheritance and composition in guisand more as we'll seeobject-oriented programming (oopisn' required for tkinterbut it makes guis structured and reusable
4,928
related tools most of the interface devices you're accustomed to seeing--slidersmenusdialogsimagesand their kin--show up here these two are not fully complete tkinter reference (which could easily fill large book by itself)but they should be enough to help you get started coding substantial python guis the examples in these are focused on widgets and tkinter toolsbut python' support for code reuse is also explored along the way covers more advanced gui programming techniques it includes an exploration of techniques for automating common gui tasks with python although tkinter is full-featured librarya small amount of reusable python code can make its interfaces even more powerful and easier to use wraps up by presenting handful of complete gui programs that make use of coding and widget techniques presented in the four preceding we'll learn how to implement text editorsimage viewersclocksand more because guis are actually cross-domain toolsother gui examples will also show up throughout the remainder of this book for examplewe'll later see complete email guis and calculatorsas well as basic ftp client guiadditional examples such as tree viewers and table browsers are available externally in the book examples package gives list of forward pointers to other tkinter examples in this text after we explore guisin part iv we'll also learn how to build basic user interfaces within web browser using html and python scripts that run on server-- very different model with advantages and tradeoffs all its own that are important to understand newer technologies such as the rias described later in this build on the web browser model to offer even more interface choices for nowthoughour focus here is on more traditional guis--known as "desktopapplications to someand as "standaloneguis to others as we'll see when we meet ftp and email client guis in the internet part of this bookthoughsuch programs often connect to network to do their work as well the term "widget setrefers to the objects used to build familiar point-and-click user interface devices-push buttonsslidersinput fieldsand so on tkinter comes with python classes that correspond to all the widgets you're accustomed to seeing in graphical displays besides widgetstkinter also comes with tools for other activitiessuch as scheduling events to occurwaiting for socket data to arriveand so on graphical user interfaces
4,929
one other point ' like to make right awaymost guis are dynamic and interactive interfacesand the best can do here is show static screenshots representing selected states in the interactions such programs implement this really won' do justice to most examples if you are not working along with the examples alreadyi encourage you to run the gui examples in this and later on your own on windowsthe standard python install comes with tkinter support built inso all these examples should work immediately mac os comes bundled with tkinteraware python as well for other systemspythons with tkinter support are either provided with the system itself or are readily available (see the top-level readme-pp txt file in the book examples distribution for more detailsgetting tkinter to work on your computer is worth whatever extra install details you may need to absorbthoughexperimenting with these programs is great way to learn about both gui programming and python itself also see the description of book example portability in general in this book' preface although python and tkinter are both largely platform neutralyou may run into some minor platform-specific issues if you try to run this book' examples on platforms other than that used to develop this book mac os xfor examplemight pose subtle differences in some of the examplesoperation be sure to watch this book' website for pointers and possible future patches for using the examples on other platforms has anyone noticed that - - are the first three letters of "guido"python creator guido van rossum didn' originally set out to build gui development toolbut python' ease of use and rapid turnaround have made this one of its primary roles from an implementation perspectiveguis in python are really just instances of extensionsand extensibility was one of the main ideas behind python when script builds push buttons and menusit ultimately talks to libraryand when script responds to user eventa library ultimately talks back to python it' really just an example of what is possible when python is used to script external libraries but from practical point of viewguis are critical part of modern systems and an ideal domain for tool like python as we'll seepython' simple syntax and objectoriented flavor blend well with the gui model--it' natural to represent each device drawn on screen as python class moreoverpython' quick turnaround lets programmers experiment with alternative layouts and behavior rapidlyin ways not possible with traditional development techniques in factyou can usually make change to python-based gui and observe its effects in matter of seconds don' try this with ++"here' looking at youkid
4,930
before we start wading into the tkinter pondlet' begin with some perspective on python gui options in general because python has proven to be such good match for gui workthis domain has seen much activity over the years in factalthough tkinter is by most accounts still the most widely used gui toolkit in the python worldthere are variety of ways to program user interfaces in python today some are specific to windows or windows,some are cross-platform solutionsand all have followings and strong points of their own to be fair to all the alternativeshere is brief inventory of gui toolkits available to python programmers as write these wordstkinter an open source gui library and the continuing de facto standard for portable gui development in python python scripts that use tkinter to build guis run portably on windowsx windows (unix and linux)and macintosh os xand they display native look-and-feel on each of these platforms today tkinter makes it easy to build simple and portable guis quickly moreoverit can be easily augmented with python codeas well as with larger extension packages such as pmw ( third-party widget library)tix (another widget libraryand now standard part of python)pil (an image-processing extension)and ttk (tk themed widgetsalso now standard part of python as of version more on such extensions like these later in this introduction the underlying tk library used by tkinter is standard in the open source world at large and is also used by the perlrubyphpcommon lispand tcl scripting languagesgiving it user base that likely numbers in the millions the python binding to tk is enhanced by python' simple object model--tk widgets become customizable and embeddable objectsinstead of string commands tkinter takes the form of module package in python xwith nested modules that group some of its tools by functionality (it was formerly known as module tkinter in python xbut was renamed to follow naming conventionsand restructured to provide more hierarchical organizationtkinter is maturerobustwidely usedand well documented it includes roughly basic widget typesplus various dialogs and other tools moreoverthere is dedicated book on the subjectplus large library of published tkinter and tk documentation perhaps most importantlybecause it is based on library in this book"windowsrefers to the microsoft windows interface common on pcsand " windowsrefers to the interface most commonly found on unix and linux platforms these two interfaces are generally tied to the microsoft and unix (and unix-likeplatformsrespectively it' possible to run windows on top of microsoft operating system and windows emulators on unix and linuxbut it' not common as if to muddy the waters furthermac os supports python' tkinter on both windows and the native aqua gui system directlyin addition to platform-specific cocoa options (though it' usually not too misleading to lump os in with the "unix-likecrowd graphical user interfaces
4,931
and as such it meshes well with scripting language like python because of such attributespython' tkinter module ships with python as standard library module and is the basis of python' standard idle integrated development environment gui in facttkinter is the only gui toolkit that is part of pythonall others on this list are third-party extensions the underlying tk library is also shipped with python on some platforms (including windowsmac os xand most linux and unix-like systemsyou can be reasonably sure that tkinter will be present when your script runsand you can guarantee this if needed by freezing your gui into self-contained binary executable with tools like pyinstaller and py exe (see the web for detailsalthough tkinter is easy to useits text and canvas widgets are powerful enough to implement web pagesthree-dimensional visualizationand animation in additiona variety of systems aim to provide gui builders for python/tkinter todayincluding gui builder (formerly part of the komodo ide and relative of spectcl)rapyd-tkxropeand others (though this set has historically tended to change much over timesee web for updatesas we will seethoughtkinter is usually so easy to code that gui builders are not widely used this is especially true once we leave the realm of the static layouts that builders typically support wxpython python interface for the open source wxwidgets (formerly called wxwindowslibrarywhich is portable gui class framework originally written to be used from the +programming language the wxpython system is an extension module that wraps wxwidgets classes this library is generally considered to excel at building sophisticated interfaces and is probably the second most popular python gui toolkit todaybehind tkinter guis coded in python with wxpython are portable to windowsunix-like platformsand mac os because wxpython is based on +class librarymost observers consider it to be more complex than tkinterit provides hundreds of classesgenerally requires an object-oriented coding styleand has design that some find reminiscent of the mfc class library on windows wxpython often expects programmers to write more codepartly because it is more functional and thus complex systemand partly because it inherits this mindset from its underlying +library moreoversome of wxpython' documentation is oriented toward ++though this story has been improved recently with the publication of book dedicated to wxpython by contrasttkinter is covered by one book dedicated to itlarge sections of other python booksand an even larger library of existing literature on the underlying tk toolkit since the world of python books has been remarkably dynamic over the yearsthoughyou should investigate the accuracy of these observations at the time that you read these wordssome books fadewhile new python books appear on regular basis python gui development options
4,932
powerful toolkit wxpython comes with richer set of widgets out of the box than tkinterincluding trees and html viewers--things that may require extensions such as pmwtixor ttk in tkinter in additionsome prefer the appearance of the interfaces it renders boaconstructor and wxdesigneramong other optionsprovide gui builder that generates wxpython code some wxwidgets tools also support non-gui python work as well for quick look at wxpython widgets and coderun the demo that comes with the system (see the web for linkspyqt python interface to the qt toolkit (now from nokiaformerly by trolltech)and perhaps the third most widely used gui toolkit for python today pyqt is fullfeatured gui library and runs portably today on windowsmac os xand unix and linux like wxpythonqt is generally more complexyet more feature richthan tkinterit contains hundreds of classes and thousands of functions and methods qt grew up on linux but became portable to other systems over timereflecting this heritagethe pyqt and pykde extension packages provide access to kde development libraries (pykde requires pyqtthe blackadder and qt designer systems provide gui builders for pyqt perhaps qt' most widely cited drawback in the past has been that it was not completely open source for full commercial use todayqt provides both gpl and lgpl open source licensingas well as commercial license options the lgpl and gpl versions are open sourcebut conform to gpl licensing constraints (gpl may also impose requirements beyond those of the python bsd-style licenseyou mustfor examplemake your source code freely available to end userspygtk python interface to gtka portable gui library originally used as the core of the gnome window system on linux the gnome-python and pygtk extension packages export gnome and gtk toolkit calls at this writingpygtk runs portably on windows and posix systems such as linux and mac os (according to its documentationit currently requires that an server for mac os has been installedthough native mac version is in the worksjython jython (the system formerly known as jpythonis python implementation for javawhich compiles python source code to java bytecodeand gives python scripts seamless access to java class libraries on the local machine because of thatjava gui libraries such as swing and awt become another way to construct guis in python code run by the jpython system such solutions are obviously java specific and limited in portability to that of java and its libraries furthermoreswing may be one of the largest and most complex gui option for python work new package named jtkinter also provides tkinter port to jython using java' jniif graphical user interfaces
4,933
also has internet roles we'll meet briefly in ironpython in very similar veinthe ironpython system--an implementation of the python language for the net environment and runtime enginewhichamong other thingscompiles python programs to net bytecode--also offers python scripts gui construction options in the net framework you write python codebut use #net components to construct interfacesand applications at large ironpython code can be run on net on windowsbut also on linux under the mono implementation of netand in the silverlight client-side ria framework for web browsers (discussed aheadpythoncard an open source gui builder and library built on top of the wxpython toolkit and considered by some to be one of python' closest equivalents to the kind of gui builders familiar to visual basic developers pythoncard describes itself as gui construction kit for building cross-platform desktop applications on windowsmac os xand linuxusing the python language dabo an open source gui builder also built on wxpythonand bit more dabo is portablethree-tiercross-platform desktop application development frameworkinspired by visual foxpro and written in python its tiers support database accessbusiness logicand user interface its open design is intended to eventually support variety of databases and multiple user interfaces (wxpythontkinterand even html over httprich internet applications (riasalthough web pages rendered with html are also kind of user interfacethey have historically been too limited to include in the general gui category howeversome observers would extend this category today to include systems which allow browser-based interfaces to be much more dynamic than traditional web pages have allowed because such systems provide widget toolkits rendered by web browsersthey can offer some of the same portability benefits as web pages in general the going buzzword for this brave new breed of toolkits is rich internet applications (riasit includes ajax and javascript-oriented frameworks for use on the clientsuch asflex an open source framework from adobe and part of the flash platform silverlight microsoft framework which is also usable on linux with mono' moonlightand can be accessed by python code with the ironpython system described above python gui development options
4,934
java platform for building rias which can run across variety of connected devices pyjamas an ajax-based port of the google web toolkit to pythonwhich comes with set of interface widgets and compiles python code that uses those widgets into javascriptto be run in browser on client the html standard under development proposes to address this domain as well web browsers ultimately are "desktopgui applicationstoobut are more pervasive than gui librariesand can be generalized with ria tools to render other guis while it' possible to build widget-based gui with such frameworksthey can also add overheads associated with networking in general and often imply substantially heavier software stack than traditional gui toolkits indeedin order to morph browsers into general gui platformsrias may imply extra software layers and dependenciesand even multiple programming languages because of thatand because not everyone codes for the web today (despite what you may have heard)we won' include them in our look at traditional standalone/desktop guis in this part of the book see the internet part for more on rias and user interfaces based on browsersand be sure to watch for news and trends on this front over time the interactivity these tools provide is also key part of what some refer to as "web when viewed more from the perspective of the web than guis since we're concerned with the latter here (and since user interaction is user interaction regardless of what jargon we use for it)we'll postpone further enumeration of this topic until the next part of the book platform-specific options besides the portable toolkits like tkinterwxpythonand pyqtand platformagnostic approaches such as riasmost major platforms have nonportable options for python-coded guis as well for instanceon macintosh os xpyobjc provides python binding to apple' objective- /cocoa frameworkwhich is the basis for much mac development on windowsthe pywin extensions package for python includes wrappers for the +microsoft foundation classes (mfcframework ( library that includes interface components)as well as pythonwinan mfc sample program that implements python development gui although net technically runs on linuxtoothe ironpython system mentioned earlier offers additional windows-focused options see the websites of these toolkits for more details there are other lesser-known gui toolkits for pythonand new ones are likely to emerge by the time you read this book (in factironpython was new in the third editionand rias are new in the fourthmoreoverpackages like those in this list are prone to mutate over time for an up-todate list of available toolssearch the web or browse pypi third-party packages index maintained there graphical user interfaces
4,935
of all the prior section' gui optionsthoughtkinter is by far the de facto standard way to implement portable user interfaces in python todayand the focus of this part of the book the rationale for this approach was explained in in shortwe elected to present one toolkit in satisfying depth instead of many toolkits in less-thanuseful fashion moreovermost of the tkinter programming concepts you learn here will translate directly to any other gui toolkit you choose to utilize tkinter pragmatics perhaps more to the pointthoughthere are pragmatic reasons that the python world still gravitates to tkinter as its de facto standard portable gui toolkit among themtkinter' accessibilityportabilityavailabilitydocumentationand extensions have made it the most widely used python gui solution for many years runningaccessibility tkinter is generally regarded as lightweight toolkit and one of the simplest gui solutions for python available today unlike larger frameworksit is easy to get started in tkinter right awaywithout first having to grasp much larger class interaction model as we'll seeprogrammers can create simple tkinter guis in few lines of python code and scale up to writing industrial-strength guis gradually although the tkinter api is basicadditional widgets can be coded in python or obtained in extension packages such as pmwtixand ttk portability python script that builds gui with tkinter will run without source code changes on all major windowing platforms todaymicrosoft windowsx windows (on unix and linux)and the macintosh os (and also ran on mac classicsfurtherthat same script will provide native look-and-feel to its users on each of these platforms in factthis feature became more apparent as tk matured pythontkinter script today looks like windows program on windowson unix and linuxit provides the same interaction but sports an appearance familiar to windows usersand on the macit looks like mac program should availability tkinter is standard module in the python libraryshipped with the interpreter if you have pythonyou have tkinter moreovermost python installation packages (including the standard python self-installer for windowsthat provided on mac os xand many linux distributionscome with tkinter support bundled because of thatscripts written to use the tkinter module work immediately on most python interpreterswithout any extra installation steps tkinter is also generally better supported than its alternatives today because the underlying tk library is also used by the tcl and perl programming languages (and others)it tends to receive more development resources than other toolkits available tkinter overview
4,936
using gui toolkittoolet' take quick look at the story tkinter has to tell on these fronts as well tkinter documentation this book explores tkinter fundamentals and most widgets toolsand it should be enough to get started with substantial gui development in python on the other handit is not an exhaustive reference to the tkinter library or extensions to it happilyat least one book dedicated to using tkinter in python is now commercially available as write this paragraphand others are on the way (search the web for detailsbesides booksyou can also find tkinter documentation onlinea complete set of tkinter manuals is currently maintained on the web at in additionbecause the underlying tk toolkit used by tkinter is also de facto standard in the open source scripting community at largeother documentation sources apply for instancebecause tk has also been adopted by the tcl and perl programming languagestk-oriented books and documentation written for both of these are directly applicable to python/tkinter as well (albeitwith some syntactic mappingfranklyi learned tkinter by studying tcl/tk texts and references--just replace tcl strings with python objects and you have additional reference libraries at your disposal (see table - the tk-to-tkinter conversion guideat the end of this for help reading tk documentationfor instancethe book tcl/tk pocket reference ( 'reillycan serve as nice supplement to the tkinter tutorial material in this part of the book moreoversince tk concepts are familiar to large body of programmerstk support is also readily available on the net after you've learned the basicsexamples can helptoo you can find tkinter demo programsbesides those you'll study in this bookat various locations around the web python itself includes set of demo programs in the demos\tkinter subdirectory of its source distribution package the idle development gui mentioned in the next section makes for an interesting code read as well tkinter extensions because tkinter is so widely usedprogrammers also have access to precoded python extensions designed to work with or augment it some of these may not yet be available for python as write this but are expected to be soon for instancepmw python mega widgets is an extension toolkit for building high-level compound widgets in python using the tkinter module it extends the tkinter api with collection of more sophisticated widgets for advanced gui development and framework for implementing some of your own among the precoded and extensible megawidgets shipped with the package are notebookscombo boxesselection graphical user interfaces
4,937
helpand an interface to the blt graph widget the interface to pmw megawidgets is similar to that of basic tkinter widgetsso python scripts can freely mix pmw megawidgets with standard tkinter widgets moreoverpmw is pure python codeand so requires no compiler or tools to install to view its widgets and the corresponding code you use to construct themrun the demos\all py script in the pmw distribution package you can find pmw at tix tix is collection of more than advanced widgetsoriginally written for tcl/tk but now available for use in python/tkinter programs this package is now python standard library modulecalled tkinter tix like tkthe underlying tix library is also shipped today with python on windows in other wordson windowsif you install pythonyou also have tix as preinstalled library of additional widgets tix includes many of the same devices as pmwincluding spin boxestreestabbed notebooksballoon help pop upspaned windowsand much more see the python library manual' entry for the tix module for more details for quick look at its widgetsas well as the python source code used to program themrun the tixwidgets py demonstration program in the demo\tix directory of the python source distribution (this directory is not installed by default on windows and is prone to change--you can generally find it after fetching and unpacking python' source code from python orgttk tk themed widgetsttkis relatively new widget set which attempts to separate the code implementing widget' behavior from that implementing its appearance widget classes handle state and callback invocationwhereas widget appearance is managed separately by themes much like tixthis extension began life separatelybut was very recently incorporated into python' standard library in python as module tkinter ttk also like tixthis extension comes with advanced widget typessome of which are not present in standard tkinter itself specificallyttk comes with widgets of which are already present in tkinter and are meant as replacements for some of tkinter' standard widgetsand of which are new--comboboxnotebookprogressbarseparatorsizegrip and treeview in nutshellscripts import from the ttk module after tkinter in order to use its replacement widgets and configure style objects possibly shared by multiple widgetsinstead of configuring widgets themselves as we'll see in this it' possible to provide common look-and-feel for set of widgets with standard tkinterby subclassing its widget classes using normal oop techniques (see "customizing widgets with classeson page howeverttk offers additional style options and advanced widget types for more details tkinter overview
4,938
book focuses on tkinter fundamentalsand tix and ttk are both too large to cover in useful fashion here pil the python imaging library (pilis an open source extension package that adds image-processing tools to python among other thingsit provides tools for image thumbnailstransformsand conversionsand it extends the basic tkinter image object to add support for displaying many image file types pilfor instanceallows tkinter guis to display jpegtiffand png images not supported by the base tkinter toolkit itself (without extensiontkinter supports gifs and handful of bitmap formatssee the end of for more details and exampleswe'll use pil in this book in number of image-related example scripts pil can be found at idle the idle integrated python development environment is both written in python with tkinter and shipped and installed with the python package (if you have recent python interpreteryou should have idle tooon windowsclick the start buttonselect the programs menuand click the python entry to find itidle provides syntax-coloring text editors for python codepoint-and-click debuggingand moreand is an example of tkinter' utility others many of the extensions that provide visualization tools for python are based on the tkinter library and its canvas widget see the pypi website and your favorite web search engine for more tkinter extension examples if you plan to do any commercial-grade gui development with tkinteryou'll probably want to explore extensions such as pmwpiltixand ttk after learning tkinter basics in this text they can save development time and add pizzazz to your guis see the python-related websites mentioned earlier for up-to-date details and links tkinter structure from more nuts-and-bolts perspectivetkinter is an integration system that implies somewhat unique program structure we'll see what this means in terms of code in momentbut here is brief introduction to some of the terms and concepts at the core of python gui programming implementation structure strictly speakingtkinter is simply the name of python' interface to tk-- gui library originally written for use with the tcl programming language and developed by tcl' creatorjohn ousterhout python' tkinter module talks to tkand the tk library in turn interfaces with the underlying window systemmicrosoft windowsx windows graphical user interfaces
4,939
of tkinter actually stems from the underling tk library it wraps python' tkinter adds software layer on top of tk that allows python scripts to call out to tk to build and configure interfaces and routes control back to python scripts that handle user-generated events ( mouse clicksthat isgui calls are internally routed from python scriptto tkinterto tkgui events are routed from tkto tkinterand back to python script in we'll know these transfers by their integration termsextending and embedding technicallytkinter is today structured as combination of the python-coded tkinter module package' files and an extension module called _tkinter that is written in _tkinter interfaces with the tk library using extending tools and dispatches callbacks back to python objects using embedding toolstkinter simply adds class-based interface on top of _tkinter you should almost always import tkinter in your scriptsthoughnot _tkinterthe latter is an implementation module meant for internal use only (and was oddly named for that reasonprogramming structure luckilypython programmers don' normally need to care about all this integration and call routing going on internallythey simply make widgets and register python functions to handle widget events because of the overall structurethoughevent handlers are usually known as callback handlersbecause the gui library "calls backto python code when events occur in factwe'll find that python/tkinter programs are entirely event driventhey build displays and register handlers for eventsand then do nothing but wait for events to occur during the waitthe tk gui library runs an event loop that watches for mouse clickskeyboard pressesand so on all application program processing happens in the registered callback handlers in response to events furtherany information needed across events must be stored in long-lived references such as global variables and class instance attributes the notion of traditional linear program control flow doesn' really apply in the gui domainyou need to think in terms of smaller chunks in pythontk also becomes object oriented simply because python is object orientedthe tkinter layer exports tk' api as python classes with tkinterwe can either use simple function-call approach to create widgets and interfacesor apply object-oriented techniques such as inheritance and composition to customize and extend the base set of tkinter classes larger tkinter guis are generally constructed as trees of linked tkinter widget objects and are often implemented as python classes to provide structure and retain state information between events as we'll see in this part of the booka tkinter gui coded with classes almost by default becomes reusable software component tkinter overview
4,940
on to the codelet' start out by quickly stepping through few small examples that illustrate basic concepts and show the windows they create on the computer display the examples will become progressively more sophisticated as we move alongbut let' get handle on the fundamentals first "hello worldin four lines (or lessthe usual first example for gui systems is to show how to display "hello worldmessage in window as coded in example - it' just four lines in python example - pp \gui\intro\gui py from tkinter import label widget label(nonetext='hello gui world!'widget pack(widget mainloop(get widget object make one arrange it start event loop this is complete python tkinter gui program when this script is runwe get simple window with label in the middleit looks like figure - on my windows laptop ( stretched some windows in this book horizontally to reveal their window titlesyour platform' window system may varyfigure - "hello world(gui on windows this isn' much to write home about yetbut notice that this is completely functionalindependent window on the computer' display it can be maximized to take up the entire screenminimized to hide it in the system barand resized click on the window' "xbox in the top right to kill the window and exit the program the script that builds this window is also fully portable run this script on your machine to see how it renders when this same file is run on linux it produces similar windowbut it behaves according to the underlying linux window manager even on the same operating systemthe same python code might yields different look-and-feel for different window systems (for instanceunder kde and gnome on linuxthe same script file would look different still when run on macintosh and other unix-like window managers on all platformsthoughits basic functional behavior will be the same graphical user interfaces
4,941
the gui script is trivial examplebut it illustrates steps common to most tkinter programs this python code does the following loads widget class from the tkinter module makes an instance of the imported label class packs (arrangesthe new label in its parent widget calls mainloop to bring up the window and start the tkinter event loop the mainloop method called last puts the label on the screen and enters tkinter wait statewhich watches for user-generated gui events within the mainloop functiontkinter internally monitors things such as the keyboard and mouse to detect usergenerated events in factthe tkinter mainloop function is similar in spirit to the following pseudo-python codedef mainloop()while the main window has not been closedif an event has occurredrun the associated event handler function because of this modelthe mainloop call in example - never returns to our script while the gui is displayed on-screen +when we write larger scriptsthe only way we can get anything done after calling mainloop is to register callback handlers to respond to events this is called event-driven programmingand it is perhaps one of the most unusual aspects of guis gui programs take the form of set of event handlers that share saved information rather than of single main control flow we'll see how this looks in terms of real code in later examples note that for code in script fileyou really need to do steps and in the preceding list to open this script' gui to display gui' window at allyou need to call main loopto display widgets within the windowthey must be packed (or otherwise arrangedso that the tkinter geometry manager knows about them in factif you call either mainloop or pack without calling the otheryour window won' show up as expecteda mainloop without pack shows an empty windowand pack without mainloop in script shows nothing since the script never enters an event wait state (try itthe mainloop call is sometimes optional when you're coding interactivelybut you shouldn' rely on this in general since the concepts illustrated by this simple script are at the core of most tkinter programslet' take deeper look at some of them before moving on +technicallythe mainloop call returns to your script only after the tkinter event loop exits this normally happens when the gui' main window is closedbut it may also occur in response to explicit quit method calls that terminate nested event loops but leave open the gui at large you'll see why this matters in climbing the gui learning curve
4,942
when widgets are constructed in tkinterwe can specify how they should be configured the gui script passes two arguments to the label class constructorthe first is parent-widget objectwhich we want the new label to be attached to herenone means "attach the new label to the default top-level window of this program laterwe'll pass real widgets in this position to attach our labels to other container objects the second is configuration option for the labelpassed as keyword argumentthe text option specifies text string to appear as the label' message most widget constructors accept multiple keyword arguments for specifying variety of options (colorsizecallback handlersand so onmost widget configuration options have reasonable defaults per platformthoughand this accounts for much of tkinter' simplicity you need to set most options only if you wish to do something custom as we'll seethe parent-widget argument is the hook we use to build up complex guis as widget trees tkinter works on "what-you-build-is-what-you-getprinciple--we construct widget object trees as models of what we want to see on the screenand then ask the tree to display itself by calling mainloop geometry managers the pack widget method called by the gui script invokes the packer geometry managerone of three ways to control how widgets are arranged in window tkinter geometry managers simply arrange one or more widgets within container (sometimes called parent or masterboth top-level windows and frames ( special kind of widget we'll meet latercan serve as containersand containers may be nested inside other containers to build hierarchical displays the packer geometry manager uses constraint option settings to automatically position widgets in window scripts supply higher-level instructions ( "attach this widget to the top of its containerand stretch it to fill its space vertically")not absolute pixel coordinates because such constraints are so abstractthe packer provides powerful and easy-to-use layout system in factyou don' even have to specify constraints if you don' pass any arguments to packyou get default packingwhich attaches the widget to the top side of its container we'll visit the packer repeatedly in this and use it in many of the examples in this book in we will also meet an alternative grid geometry manager-- layout system that arranges widgets within container in tabular form ( by rows and columnsand works well for input forms third alternativecalled the placer geometry manager systemis described in tk documentation but not in this bookit' less popular than the pack and grid managers and can be difficult to use for larger guis coded by hand graphical user interfaces
4,943
like all python codethe module in example - can be started in number of ways-by running it as top-level program filec:\pp \gui\intropython gui py by importing it from python session or another module fileimport gui by running it as unix executable if we add the special #line at the topgui py and in any other way python programs can be launched on your platform for instancethe script can also be run by clicking on the file' name in windows file explorerand its code can be typed interactively at the prompt ss it can even be run from program by calling the appropriate embedding api function (see for details on integrationin other wordsthere are really no special rules to follow when launching gui python code the tkinter interface (and tk itselfis linked into the python interpreter when python program calls gui functionsthey're simply passed to the embedded gui system behind the scenes that makes it easy to write command-line tools that pop up windowsthey are run the same way as the purely text-based scripts we studied in the prior part of this book avoiding dos consoles on windows in and we noted that if program' name ends in pyw extension rather than py extensionthe windows python port does not pop up dos console box to serve as its standard streams when the file is launched by clicking its filename icon now that we've finally started making windows of our ownthat filename trick will start to become even more useful if you just want to see the windows that your script makes no matter how it is launchedbe sure to name your gui scripts with pyw if they might be run on windows for instanceclicking on the file in example - in windows explorer creates just the window in figure - example - pp \gui\intro\gui pyw same as gui py ss tipas suggested earlierwhen typing tkinter gui code interactivelyyou may or may not need to call mainloop to display widgets this is required in the current idle interfacebut not from simple interactive session running in system console window in either casecontrol will return to the interactive prompt when you kill the window you created note that if you create an explicit main-window widget by calling tk(and attach widgets to it (described later)you must call this again after killing the windowotherwisethe application window will not exist climbing the gui learning curve
4,944
pythonw exe executablenot python exe (in factpyw files are simply registered to be opened by pythonwon linuxthe pyw doesn' hurtbut it isn' necessarythere is no notion of streams pop up on unix-like machines on the other handif your gui scripts might run on windows in the futureadding an extra "wat the end of their names now might save porting effort later in this bookpy filenames are still sometimes used to pop up console windows for viewing printed messages on windows tkinter coding alternatives as you might expectthere are variety of ways to code the gui example for instanceif you want to make all your tkinter imports more explicit in your scriptgrab the whole module and prefix all of its names with the module' nameas in example - example - pp \gui\intro\gui py--import versus from import tkinter widget tkinter label(nonetext='hello gui world!'widget pack(widget mainloop(that will probably get tedious in realistic examplesthough--tkinter exports dozens of widget classes and constants that show up all over python gui scripts in factit is usually easier to use to import everything from the tkinter module by name in one shot this is demonstrated in example - example - pp \gui\intro\gui py--rootssidespack in place from tkinter import root tk(label(roottext='hello gui world!'pack(side=toproot mainloop(the tkinter module goes out of its way to export only what we really needso it' one of the few for which the import form is relatively safe to apply |the top constant in the pack call herefor instanceis one of those many names exported by the tkinter module it' simply variable name (top="top"preassigned in constantsa module automatically loaded by tkinter when widgets are packedwe can specify which side of their parent they should be attached to--topbottomleftor right if no side option is sent to pack (as in prior examples) widget is attached to its parent' top by default in generallarger tkinter guis can be constructed as sets of rectanglesattached to the appropriate sides of other|if you study the main tkinter file in the python source library (currentlylib\tkinter\__init__ py)you'll notice that top-level module names not meant for export start with single underscore python never copies over such names when module is accessed with the form of the from statement the constants module is today constants py in the same module package directorythough this can change (and hasover time graphical user interfaces
4,945
to both their packing order and their side attachment options when widgets are griddedthey are assigned row and column numbers instead none of this will become very meaningfulthoughuntil we have more than one widget in windowso let' move on notice that this version calls the pack method right away after creating the labelwithout assigning it variable if we don' need to save widgetwe can pack it in place like this to eliminate statement we'll use this form when widget is attached to larger structure and never again referenced this can be tricky if you assign the pack resultthoughbut 'll postpone an explanation of why until we've covered few more basics we also use tk widget class instanceinstead of noneas the parent here tk represents the main ("root"window of the program--the one that starts when the program does an automatically created tk instance is also used as the default parent widgetboth when we don' pass any parent to other widget calls and when we pass the parent as none in other wordswidgets are simply attached to the main program window by default this script just makes this default behavior explicit by making and passing the tk object itself in we'll see that toplevel widgets are typically used to generate new pop-up windows that operate independently of the program' main window in tkintersome widget methods are exported as functionsand this lets us shave example - to just three lines of code example - pp \gui\intro\gui py-- minimal version from tkinter import label(text='hello gui world!'pack(mainloop(the tkinter mainloop can be called with or without widget ( as function or methodwe didn' pass label parent argument in this versioneitherit simply defaults to none when omitted (which in turn defaults to the automatically created tk objectbut relying on that default is less useful once we start building larger displays things such as labels are more typically attached to other widget containers widget resizing basics top-level windowssuch as the one built by all of the coding variants we have seen thus farcan normally be resized by the usersimply drag out the window with your mouse figure - shows how our window looks when it is expanded this isn' very good--the label stays attached to the top of the parent window instead of staying in the middle on expansion--but it' easy to improve on this with pair of pack optionsdemonstrated in example - tkinter coding alternatives
4,946
example - pp \gui\intro\gui py--expansion from tkinter import label(text='hello gui world!'pack(expand=yesfill=bothmainloop(when widgets are packedwe can specify whether widget should expand to take up all available spaceand if sohow it should stretch to fill that space by defaultwidgets are not expanded when their parent is but in this scriptthe names yes and both (imported from the tkinter modulespecify that the label should grow along with its parentthe main window it does so in figure - figure - gui with widget resizing technicallythe packer geometry manager assigns size to each widget in display based on what it contains (text string lengthsetc by defaulta widget can occupy only its allocated space and is no bigger than its assigned size the expand and fill options let us be more specific about such things graphical user interfaces
4,947
asks the packer to expand the allocated space for the widget in general into any unclaimed space in the widget' parent fill option can be used to stretch the widget to occupy all of its allocated space combinations of these two options produce different layout and resizing effectssome of which become meaningful only when there are multiple widgets in window for exampleusing expand without fill centers the widget in the expanded spaceand the fill option can specify vertical stretching only (fill= )horizontal stretching only (fill= )or both (fill=bothby providing these constraints and attachment sides for all widgets in guialong with packing orderwe can control the layout in fairly precise terms in later we'll find that the grid geometry manager uses different resizing protocol entirelybut it provides similar control when needed all of this can be confusing the first time you hear itand we'll return to this later but if you're not sure what an expand and fill combination will dosimply try it out--this is pythonafter all for nowremember that the combination of expand=yes and fill=both is perhaps the most common settingit means "expand my space allocation to occupy all available space on my sideand stretch me to fill the expanded space in both directions for our "hello worldexamplethe net result is that the label grows as the window is expandedand so is always centered configuring widget options and window titles so farwe've been telling tkinter what to display on our label by passing its text as keyword argument in label constructor calls it turns out that there are two other ways to specify widget configuration options in example - the text option of the label is set after it is constructedby assigning to the widget' text key widget objects overload (interceptindex operations such that options are also available as mapping keysmuch like dictionary example - pp \gui\intro\gui py--option keys from tkinter import widget label(widget['text''hello gui world!widget pack(side=topmainloop(more commonlywidget options can be set after construction by calling the widget config methodas in example - tkinter coding alternatives
4,948
from tkinter import root tk(widget label(rootwidget config(text='hello gui world!'widget pack(side=topexpand=yesfill=bothroot title('gui py'root mainloop(the config method (which can also be called by its synonymconfigurecan be called at any time after construction to change the appearance of widget on the fly for instancewe could call this label' config method again later in the script to change the text that it displayswatch for such dynamic reconfigurations in later examples in this part of the book notice that this version also calls root title methodthis call sets the label that appears at the top of the windowas pictured in figure - in general termstop-level windows like the tk root here export window-manager interfaces-- things that have to do with the border around the windownot its contents figure - gui with expansion and window title just for funthis version also centers the label upon resizes by setting the expand and fill pack options in factthis version makes just about everything explicit and is more representative of how labels are often coded in full-blown interfacestheir parentsexpansion policiesand attachments are usually spelled out rather than defaulted one more for old timessake finallyif you are minimalist and you're nostalgic for old python coding stylesyou can also program this "hello worldexample as in example - example - pp \gui\intro\gui -old py--dictionary calls from tkinter import label(none{'text''hello gui world!'pack{'side''top'}}mainloop( graphical user interfaces
4,949
relies on an old coding style that was widely used until python which passed configuration options in dictionary instead of keyword arguments in this schemepacker options can be sent as values of the key pack ( class in the tkinter modulethe dictionary call scheme still works and you may see it in old python codebut it' probably best to not do this in code you type use keywords to pass optionsand use explicit pack method calls in your tkinter scripts instead in factthe only reason didn' cut this example completely is that dictionaries can still be useful if you want to compute and pass set of options dynamically on the other handthe func(*pargs**kargssyntax now also allows you to pass an explicit dictionary of keyword arguments in its third argument slotoptions {'text''hello gui world!'layout {'side''top'label(none**optionspack(**layoutkeyword must be strings even in dynamic scenarios where widget options are determined at run timethere' no compelling reason to ever use the pre- tkinter dictionary call form packing widgets without saving them in gui py (shown in example - ) started packing labels without assigning them to names this worksand it is an entirely valid coding stylebut because it tends to confuse beginners at first glancei need to explain why it works in more detail here in tkinterpython class objects correspond to real objects displayed on screenwe make the python object to make screen objectand we call the python object' methods to configure that screen object because of this correspondencethe lifetime of the python object must generally correspond to the lifetime of the corresponding object on the screen luckilypython scripts don' usually have to care about managing object lifetimes in factthey do not normally need to maintain reference to widget objects created along the way at all unless they plan to reconfigure those objects later for instanceit' common in tkinter programming to pack widget immediately after creating it if no further reference to the widget is requiredlabel(text='hi'pack(ok this expression is evaluated left to rightas usual it creates new label and then immediately calls the new object' pack method to arrange it in the display noticethoughthat the python label object is temporary in this expressionbecause it is not #in factpython' pass-by-name keyword arguments were first introduced to help clean up tkinter calls such as this one internallykeyword arguments really are passed as dictionary (which can be collected with the **name argument form in def header)so the two schemes are similar in implementation but they vary widely in the number of characters you need to type and debug tkinter coding alternatives
4,950
by python immediately after running its pack method howeverbecause tkinter emits tk calls when objects are constructedthe label will be drawn on the display as expectedeven though we haven' held onto the corresponding python object in our script in facttkinter internally cross-links widget objects into long-lived tree used to represent the displayso the label object made during this statement actually is retainedeven if not by our code in other wordsyour scripts don' generally have to care about widget object lifetimesand it' ok to make widgets and pack them immediately in the same statement without maintaining reference to them explicitly in your code but that does not mean that it' ok to say something like thiswidget label(text='hi'pack(use widget wrongthis statement almost seems like it should assign newly packed label to widgetbut it does not do this in factit' really notorious tkinter beginner' mistake the widget pack method packs the widget but does not return the widget thus packed reallypack returns the python object noneafter such statementwidget will be reference to noneand any further widget operations through that name will fail for instancethe following failstoofor the same reasonlabel(text='hi'pack(mainloop(wrongsince pack returns noneasking for its mainloop attribute generates an exception (as it shouldif you really want to both pack widget and retain reference to itsay this insteadwidget label(text='hi'widget pack(use widget ok too this form is bit more verbose but is less tricky than packing widget in the same statement that creates itand it allows you to hold onto the widget for later processing it' probably more common in realistic scripts that perform more complex widget configuration and layouts on the other handscripts that compose layouts often add some widgets once and for all when they are created and never need to reconfigure them laterassigning to longlived names in such programs is pointless and unnecessary ex-tcl programmers in the audience may be interested to know thatat least at the time was writing this footnotepython not only builds the widget tree internallybut uses it to automatically generate widget pathname strings coded manually in tcl/tk ( panel row cmdpython uses the addresses of widget class objects to fill in the path components and records pathnames in the widget tree label attached to containerfor instancemight have an assigned name such as inside tkinter you don' have to carethough simply make and link widget objects by passing parentsand let python manage pathname details based on the object tree see the end of this for more on tk/tkinter mappings graphical user interfaces
4,951
data is discarded if the python image object is garbage collected tkinter variable class objects also temporarily unset an associated tk variable if reclaimedbut this is uncommon and less harmful adding buttons and callbacks so farwe've learned how to display messages in labelsand we've met tkinter core concepts along the way labels are nice for teaching the basicsbut user interfaces usually need to do bit more like actually responding to users to show howthe program in example - creates the window in figure - example - pp \gui\intro\gui py import sys from tkinter import widget button(nonetext='hello widget world'command=sys exitwidget pack(widget mainloop(figure - button on the top hereinstead of making labelwe create an instance of the tkinter button class it' attached to the default top level window as before on the default top packing side but the main thing to notice here is the button' configuration argumentswe set an option called command to the sys exit function for buttonsthe command option is the place where we specify callback handler function to be run when the button is later pressed in effectwe use command to register an action for tkinter to call when widget' event occurs the callback handler used here isn' very interestingas we learned in the built-in sys exit function simply shuts down the calling program herethat means that pressing this button makes the window go away just as for labelsthere are other ways to code buttons example - is version that packs the button in place without assigning it to nameattaches it to the left side of its parent window explicitlyand specifies root quit as the callback handler-- standard tk object method that shuts down the gui and so ends the program technicallyquit ends the current mainloop event loop calland thus the entire program herewhen adding buttons and callbacks
4,952
closes all windowsbut its relative destroy erases just one window example - pp \gui\intro\gui py from tkinter import root tk(button(roottext='press'command=root quitpack(side=leftroot mainloop(this version produces the window in figure - because we didn' tell the button to expand into all available spaceit does not do so figure - button on the left in both of the last two examplespressing the button makes the gui program exit in older tkinter codeyou may sometimes see the string exit assigned to the command option to make the gui go away when pressed this exploits tool in the underlying tk library and is less pythonic than sys exit or root quit widget resizing revisitedexpansion even with gui this simplethere are many ways to lay out its appearance with tkinter' constraint-based pack geometry manager for exampleto center the button in its windowadd an expand=yes option to the button' pack method call in example - the line of changed code looks like thisbutton(roottext='press'command=root quitpack(side=leftexpand=yesthis makes the packer allocate all available space to the button but does not stretch the button to fill that space the result is the window captured in figure - figure - pack(side=leftexpand=yesif you want the button to be given all available space and to stretch to fill all of its assigned space horizontallyadd expand=yes and fill= keyword arguments to the pack call this will create the scene in figure - graphical user interfaces
4,953
this makes the button fill the whole window initially (its allocation is expandedand it is stretched to fill that allocationit also makes the button grow as the parent window is resized as shown in figure - the button in this window does expand when its parent expandsbut only along the horizontal axis figure - resizing with expand=yesfill= to make the button grow in both directionsspecify both expand=yes and fill=both in the pack callnow resizing the window makes the button grow in generalas shown in figure - in factfor more funmaximize this window to fill the entire screenyou'll get one very big tkinter button indeed figure - resizing with expand=yesfill=both adding buttons and callbacks
4,954
contained by are set to expand too herethe button' only parent is the tk root window of the programso parent expandability isn' yet an issuein later exampleswe'll need to make enclosing frame widgets expandable too we will revisit the packer geometry manager when we meet multiple-widget displays that use such devices later in this tutorialand again when we study the alternative grid call in adding user-defined callback handlers in the simple button examples in the preceding sectionthe callback handler was simply an existing function that killed the gui program it' not much more work to register callback handlers that do something bit more useful example - defines callback handler of its own in python example - pp \gui\intro\gui py import sys from tkinter import def quit()print('helloi must be going 'sys exit( custom callback handler kill windows and process widget button(nonetext='hello event world'command=quitwidget pack(widget mainloop(the window created by this script is shown in figure - this script and its gui are almost identical to the last example but herethe command option specifies function we've defined locally when the button is pressedtkinter calls the quit function in this file to handle the eventpassing it zero arguments inside quitthe print call statement types message on the program' stdout streamand the gui process exits as before figure - button that runs python function as usualstdout is normally the window that the program was started from unless it' been redirected to file it' pop-up dos console if you run this program by clicking it on windowsadd an input call before sys exit if you have trouble seeing the message before the pop up disappears here' what the printed output looks like back in standard stream world when the button is pressedit is generated by python function called automatically by tkinter graphical user interfaces
4,955
helloi must be going :\pp \gui\intronormallysuch messages would be displayed in the guibut we haven' gotten far enough to know how just yet callback functions usually do moreof course (and may even pop up new independent windows altogether)but this example illustrates the basics in generalcallback handlers can be any callable objectfunctionsanonymous functions generated with lambda expressionsbound methods of class or type instancesor class instances that inherit __call__ operator overload method for button press callbackscallback handlers always receive no arguments (other than an automatic selffor bound methods)any state information required by the callback handler must be provided in other ways--as global variablesclass instance attributesextra arguments provided by an indirection layerand so on to make this bit more concretelet' take quick look at some other ways to code the callback handler in this example lambda callback handlers recall that the python lambda expression generates newunnamed function object when run if we need extra data passed in to the handler functionwe can register lambda expressions to defer the call to the real handler functionand specify the extra data it needs later in this part of the bookwe'll see how this can be more usefulbut to illustrate the basic ideaexample - shows what example - looks like when recoded to use lambda instead of def example - pp \gui\intro\gui py import sys from tkinter import lambda generates function widget button(nonebut contains just an expression text='hello event world'command=(lambdaprint('hello lambda world'or sys exit()widget pack(widget mainloop(this code is bit tricky because lambdas can contain only an expressionto emulate the original scriptthis version uses an or operator to force two expressions to be run print works as the firstbecause it' function call in python --we don' need to resort to using sys stdout directlyadding user-defined callback handlers
4,956
more typicallylambdas are used to provide an indirection layer that passes along extra data to callback handler ( omit pack and mainloop calls in the following snippets for simplicity)def handler(ab)use and would normally be called with no args button(text='ni'command=(lambdahandler( 'spam'))lambda adds arguments although tkinter invokes command callbacks with no argumentssuch lambda can be used to provide an indirect anonymous function that wraps the real handler call and passes along information that existed when the gui was first constructed the call to the real handler isin effectdeferredso we can add the extra arguments it requires herethe value of global variable and string 'spamwill be passed to arguments and beven though tkinter itself runs callbacks with no arguments the net effect is that the lambda serves to map no-argument function call to one with arguments supplied by the lambda if lambda syntax confuses youremember that lambda expression such as the one in the preceding code can usually be coded as simple def statement insteadnested or otherwise in the following codethe second function does exactly the same work as the prior lambda--by referencing it in the button creation callit effectively defers invocation of the actual callback handler so that extra arguments can be passeddef handler(ab)use and def func()handler( 'spam'would normally be called with no args indirection layer to add arguments button(text='ni'command=functo make the need for deferrals more obviousnotice what happens if you code handler call in the button creation call itself without lambda or other intermediate function-the callback runs immediately when the button is creatednot when it is later clicked that' why we need to wrap the call in an intermediate function to defer its invocationdef handler(name)print(namebutton(command=handler('spam')badruns the callback nowusing either lambda or callable reference serves to defer callback invocation until the event later occurs for exampleusing lambda to pass extra data with an inline function definition that defers the calldef handler(name)print(name graphical user interfaces
4,957
okwrap in lambda to defer is always equivalent to the longerand to some observers less convenientdoublefunction formdef handler(name)print(namedef temp()handler('spam'button(command=tempokrefence but do not call we need only the zero-argument lambda or the zero-argument callable referencethoughnot both--it makes no sense to code lambda which simply calls function if no extra data must be passed in and only adds an extra pointless calldef handler(name)print(namedef temp()handler('spam'button(command=(lambdatemp())badthis adds pointless callas we'll see laterthis includes references to other callables like bound methods and callable instances which retain state in themselves--if they take zero arguments when calledwe can simply name them at widget construction timeand we don' need to wrap them in superfluous lambda callback scope issues although the prior section' lambda and intermediate function techniques defer calls and allow extra data to be passed inthey also raise some scoping issues that may seem subtle at first glance this is core language territorybut it comes up often in practice in conjunction with gui arguments versus globals for instancenotice that the handler function in the prior section' initial code could also refer to directlybecause it is global variable (and would exist by the time the code inside the handler is runbecause of thatwe might make the handler oneargument function and pass in just the string 'spamin the lambdadef handler( )use global and argument is in my global scopeimplicitly button(text='ni'command=(lambdahandler('spam'))adding user-defined callback handlers
4,958
lambda here entirelywe could register the handler itself and cut out the middleman although simple in this trivial examplearguments are generally preferred to globalsbecause they make external dependencies more explicitand so make code easier to understand and change in factthe same handler might be usable in other contextsif we don' couple it to global variablesvalues while you'll have to take it on faith until we step up to larger examples with more complex state retention needsavoiding globals in callbacks and guis in general both makes them more reusableand supports the notion of multiple instances in the same program it' good programming practicegui or not passing in enclosing scope values with default arguments more subtlynotice that if the button in this example was constructed inside function rather than at the top level of the filename would no longer be global but would be in the enclosing function' local scopeit seems as if it would disappear after the function exits and before the callback event occurs and runs the lambda' codedef handler(ab)use and def makegui() button(text='ni'command=(lambdahandler( 'spam'))makegui(mainloop(remembers makegui' scope is gone by this point luckilypython' enclosing scope reference model means that the value of in the local scope enclosing the lambda function is automatically retainedfor use later when the button press occurs this usually works as we want todayand automatically handles variable references in this role to make such enclosing scope usage explicitthoughdefault argument values can also be used to remember the values of variables in the enclosing local scopeeven after the enclosing function returns in the following codefor instancethe default argument name (on the left side of the = defaultwill remember object because the variable name (on the right side of the =xis evaluated in the enclosing scopeand the generated function is later called without any argumentsdef handler(ab)use and older pythonsdefaults save state def makegui() button(text='ni'command=(lambda =xhandler( 'spam'))since default arguments are evaluated and saved when the lambda runs (not when the function it creates is later called)they are way to explicitly remember objects that graphical user interfaces
4,959
function later with no argumentsall its defaults are used this was not an issue in the original version of this example because name lived in the global scopeand the code of the lambda will find it there when it is run when nested within functionthoughx may have disappeared after the enclosing function exits passing in enclosing scope values with automatic references while they can make some external dependencies more explicitdefaults are not usually required (since python at leastand are not used for this role in best practice code today ratherlambdas simply defer the call to the actual handler and provide extra handler arguments variables from the enclosing scope used by the lambda are automatically retainedeven after the enclosing function exits the prior code listingfor examplecan today normally be coded as we did earlier-name in the handler will be automatically mapped to in the enclosing scopeand so effectively remember what was when the button was madedef makegui() button(text='ni'command=(lambdahandler( 'spam')) is retained auto no need for defaults we'll see this technique put to more concrete use later when using classes to build your guifor instancethe self argument is local variable in methodsand is thus automatically available in the bodies of lambda functions there is no need to pass it in explicitly with defaultsclass guidef handler(selfab)use selfa and def makegui(self) button(text='ni'command=(lambdaself handler( 'spam'))gui(makegui(mainloop(when using classesthoughinstance attributes can provide extra state for use in callback handlersand so provide an alternative to extra call arguments we'll see how in moment firstthoughwe need to take quick non-gui diversion into dark corner of python' scope rules to understand why default arguments are still sometimes necessary to pass values into nested lambda functionsespecially in guis but you must still sometimes use defaults instead of enclosing scopes although you may still see defaults used to pass in enclosing scope references in some older python codeautomatic enclosing scope references are generally preferred today in factit seems as though the newer nested scope lookup rules in python automate adding user-defined callback handlers
4,960
wellalmost there is catch it turns out that within lambda (or def)references to names in the enclosing scope are actually resolved when the generated function is callednot when it is created because of thiswhen the function is later calledsuch name references will reflect the latest or final assignments made to the names anywhere in the enclosing scopewhich are not necessarily the values they held when the function was made this holds true even when the callback function is nested only in module' global scopenot in an enclosing functionin either caseall enclosing scope references are resolved at function call timenot at function creation time this is subtly different from default argument valueswhich are evaluated once when the function is creatednot when it is later called because of thatdefaults can still be useful for remembering the values of enclosing scope variables as they were when you made the function unlike enclosing scope name referencesdefaults will not have different value if the variable later changes in the enclosing scopebetween function creation and call (in factthis is why mutable defaults like lists retain their state between calls--they are created only oncewhen the function is madeand attached to the function itself this is normally nonissuebecause most enclosing scope references name variable that is assigned just once in the enclosing scope (the self argument in class methodsfor examplebut this can lead to coding mistakes if not understoodespecially if you create functions within loopif those functions reference the loop variableit will evaluate to the value it was given on the last loop iteration in all the functions generated by contrastif you use defaults insteadeach function will remember the current value of the loop variablenot the last because of this differencenested scope references are not always sufficient to remember enclosing scope valuesand defaults are sometimes still required today let' see what this means in terms of code consider the following nested function (this section' code snippets are saved in file defaults py in the examples packageif you want to experiment with themdef simple()spam 'nidef action()print(spamreturn action act simple(act(name maps to enclosing function make and return nested function then call itprints 'nithis is the simple case for enclosing scope referencesand it works the same way whether the nested function is generated with def or lambda but notice that this still works if we assign the enclosing scope' spam variable after the nested function is created graphical user interfaces
4,961
def action()return spam spam 'nireturn action act normal(print(act()reallylooked up when used also prints 'nias this impliesthe enclosing scope name isn' resolved when the nested function is made--in factthe name hasn' even been assigned yet in this example the name is resolved when the nested function is called the same holds true for lambdasdef weird()spam return (lambdaspam remembers spam in enclosing scope act weird(print(act()prints so farso good the spam inside this nested lambda function remembers the value that this variable had in the enclosing scopeeven after the enclosing scope exits this pattern corresponds to registered gui callback handler run later on events but once againthe nested scope reference really isn' being resolved when the lambda is run to create the functionit' being resolved when the generated function is later called to make that more apparentlook at this codedef weird()tmp (lambdaspam spam return tmp act weird(print(act()remembers spam even though not set till here prints here againthe nested function refers to variable that hasn' even been assigned yet when that function is made reallyenclosing scope references yield the latest setting made in the enclosing scopewhenever the function is called watch what happens in the following codedef weird()spam handler (lambdaspam spam print(handler()spam print(handler()func doesn' save now prints spam looked up now prints spam looked up again now weird(nowthe reference to spam inside the lambda is different each time the generated function is calledin factit refers to what the variable was set to last in the enclosing scope at the time the nested function is calledbecause it is resolved at function call timenot at function creation time adding user-defined callback handlers
4,962
created within the loops if you're going to make functions within loopyou have to apply the last example' behavior to the loop variabledef odd()funcs [for in 'abcdefg'funcs append((lambdac)return funcs will be looked up later does not remember current for func in odd()print(func()end='oopsprint 'snot , ,cherethe func list simulates registered gui callback handlers associated with widgets this doesn' work the way most people expect it to the variable within the nested function will always be herethe value that the variable was set to on the final iteration of the loop in the enclosing scope the net effect is that all seven generated lambda functions wind up with the same extra state information when they are later called analogous gui code that adds information to lambda callback handlers will have similar problems--all buttons created in loopfor instancemay wind up doing the same thing when clickedto make this workwe still have to pass values into the nested function with defaults in order to save the current value of the loop variable (not its future value)def odd()funcs [for in 'abcdefg'funcs append((lambda =cc)return funcs force to remember now defaults eval now for func in odd()print(func()end='oknow prints , ,cthis works now only because the defaultunlike an external scope referenceis evaluated at function creation timenot at function call time it remembers the value that name in the enclosing scope had when the function was madenot the last assignment made to that name anywhere in the enclosing scope the same is true even if the function' enclosing scope is modulenot another functionif we don' use the default argument in the following codethe loop variable will resolve to the same value in all seven functionsfuncs [for in 'abcdefg'funcs append((lambda =cc)enclosing scope is module force to remember now else prints ' again for func in funcsprint(func()end='okprints , ,cthe moral of this story is that enclosing scope name references are replacement for passing values in with defaultsbut only as long as the name in the enclosing scope will graphical user interfaces
4,963
generally reference enclosing scope loop variables within nested functionfor examplebecause they will change as the loop progresses in most other casesthoughenclosing scope variables will take on only one value in their scope and so can be used freely we'll see this phenomenon at work in later examples that construct larger guis for nowremember that enclosing scopes are not complete replacement for defaultsdefaults are still required in some contexts to pass values into callback functions also keep in mind that classes are often better and simpler way to retain extra state for use in callback handlers than are nested functions because state is explicit in classesthese scope issues do not apply the next two sections cover this in detail bound method callback handlers let' get back to coding guis although functions and lambdas suffice in many casesbound methods of class instances work particularly well as callback handlers in guis-they record both an instance to send the event to and an associated method to call for instanceexample - shows examples - and - rewritten to register bound class method rather than function or lambda result example - pp \gui\intro\gui py import sys from tkinter import class helloclassdef __init__(self)widget button(nonetext='hello event world'command=self quitwidget pack(def quit(self)print('hello class method world'sys exit(self quit is bound method retains the self+quit pair helloclass(mainloop(on button presstkinter calls this class' quit method with no argumentsas usual but reallyit does receive one argument--the original self object--even though tkinter doesn' pass it explicitly because the self quit bound method retains both self and quitit' compatible with simple function callpython automatically passes the self argument along to the method function converselyregistering an unbound instance method that expects an argumentsuch as helloclass quitwon' workbecause there is no self object to pass along when the event later occurs adding user-defined callback handlers
4,964
remember information for use on events--simply assign the information to self instance attributesclass someguiclassdef __init__(self)self self 'spambutton(text='hi'command=self handlerdef handler(self)use self xself because the event will be dispatched to this class' method with reference to the original instance objectself gives access to attributes that retain original data in effectthe instance' attributes retain state information to be used when events occur especially in larger guisthis is much more flexible technique than global variables or extra arguments added by lambdas callable class object callback handlers because python class instance objects can also be called if they inherit __call__ method to intercept the operationwe can pass one of these to serve as callback handler too example - shows class that provides the required function-like interface example - pp \gui\intro\gui py import sys from tkinter import class hellocallabledef __init__(self)self msg 'hello __call__ worlddef __call__(self)print(self msgsys exit(__init__ run on object creation __call__ run later when called class object looks like function widget button(nonetext='hello event world'command=hellocallable()widget pack(widget mainloop(herethe hellocallable instance registered with command can be called like normal functionpython invokes its __call__ method to handle the call operation made in tkinter on the button press in effectthe general __call__ method replaces specific bound method in this case notice how self msg is used to retain information for use on events hereself is the original instance when the special __call__ method is automatically invoked all four gui variants create the same sort of gui window (figure - )but print different messages to stdout when their button is pressed graphical user interfaces
4,965
helloi must be going :\pp \gui\intropython gui py hello lambda world :\pp \gui\intropython gui py hello class method world :\pp \gui\intropython gui py hello __call__ world there are good reasons for each callback coding scheme (functionlambdaclass methodcallable class)but we need to move on to larger examples in order to uncover them in less theoretical terms other tkinter callback protocols for future referencealso keep in mind that using command options to intercept usergenerated button press events is just one way to register callbacks in tkinter in factthere are variety of ways for tkinter scripts to catch eventsbutton command options as we've just seenbutton press events are intercepted by providing callable object in widget command options this is true of other kinds of button-like widgets we'll meet in ( radio and check buttons and scalesmenu command options in the upcoming tkinter tour we'll also find that command option is used to specify callback handlers for menu selections scroll bar protocols scroll bar widgets register handlers with command optionstoobut they have unique event protocol that allows them to be cross-linked with the widget they are meant to scroll ( listboxestext displaysand canvases)moving the scroll bar automatically moves the widgetand vice versa general widget bind methods more general tkinter event bind method mechanism can be used to register callback handlers for lower-level interface events--key pressesmouse movement and clicksand so on unlike command callbacksbind callbacks receive an event object argument (an instance of the tkinter event classthat gives context about the event--subject widgetscreen coordinatesand so on window manager protocols in additionscripts can also intercept window manager events ( window close requestsby tapping into the window manager protocol method mechanism available on top-level window objects setting handler for wm_delete_windowfor instancetakes over window close buttons adding user-defined callback handlers
4,966
finallytkinter scripts can also register callback handlers to be run in special contextssuch as timer expirationsinput data arrivaland event-loop idle states scripts can also pause for state-change events related to windows and special variables we'll meet these event interfaces in more detail near the end of binding events of all the options listed in the prior sectionbind is the most generalbut also perhaps the most complex we'll study it in more detail laterbut to let you sample its flavor nowexample - rewrites the prior section' gui again to use bindnot the command keywordto catch button presses example - pp \gui\intro\gui py import sys from tkinter import def hello(event)print('press twice to exit'def quit(event)print('helloi must be going 'sys exit(on single-left click on double-left click event gives widgetx/yetc widget button(nonetext='hello event world'widget pack(widget bind(''hellobind left mouse clicks widget bind(''quitbind double-left clicks widget mainloop(in factthis version doesn' specify command option for the button at all insteadit binds lower-level callback handlers for both left mouse clicks (and doubleleft mouse clicks (within the button' display area the bind method accepts large set of such event identifiers in variety of formatswhich we'll meet in when runthis script makes the same window as before (see figure - clicking on the button once prints message but doesn' exityou need to double-click on the button now to exit as before here is the output after clicking twice and double-clicking once ( double-click fires the single-click callback first) :\pp \gui\intropython gui py press twice to exit press twice to exit press twice to exit helloi must be going although this script intercepts button clicks manuallythe end result is roughly the samewidget-specific protocols such as button command options are really just higherlevel interfaces to events you can also catch with bind graphical user interfaces
4,967
detail later in this book firstthoughlet' focus on building guis that are larger than single button and explore few other ways to use classes in gui work adding multiple widgets it' time to start building user interfaces with more than one widget example - makes the window shown in figure - example - pp \gui\intro\gui py from tkinter import def greeting()print('hello stdout world'win frame(win pack(label(wintext='hello container world'pack(side=topbutton(wintext='hello'command=greetingpack(side=leftbutton(wintext='quit'command=win quitpack(side=rightwin mainloop(figure - multiple-widget window this example makes frame widget (another tkinter classand attaches three other widget objects to ita label and two buttonsby passing the frame as their first argument in tkinter termswe say that the frame becomes parent to the other three widgets both buttons on this display trigger callbackspressing the hello button triggers the greeting function defined within this filewhich prints to stdout again pressing the quit button calls the standard tkinter quit methodinherited by win from the frame class (frame quit has the same effect as the tk quit we used earlierhere is the stdout text that shows up on hello button presseswherever this script' standard streams may bec:\pp \gui\intropython gui py hello stdout worldhello stdout worldadding multiple widgets
4,968
hello stdout worldthe notion of attaching widgets to containers turns out to be at the core of layouts in tkinter before we go into more detail on that topicthoughlet' get small widget resizing revisitedclipping earlierwe saw how to make widgets expand along with their parent windowby passing expand and fill options to the pack geometry manager now that we have window with more than one widgeti can let you in on one of the more useful secrets in the packer as rulewidgets packed first are clipped last when window is shrunk that isthe order in which you pack items determines which items will be cut out of the display if it is made too small widgets packed later are cut out first for examplefigure - shows what happens when the gui window is shrunk interactively figure - gui gets small try reordering the label and button lines in the script and see what happens when the window shrinksthe first one packed is always the last to go away for instanceif the label is packed lastfigure - shows that it is clipped firsteven though it is attached to the topside attachments and packing order both impact the overall layoutbut only packing order matters when windows shrink here are the changed linesbutton(wintext='hello'command=greetingpack(side=leftbutton(wintext='quit'command=win quitpack(side=rightlabel(wintext='hello container world'pack(side=topfigure - label packed lastclipped first tkinter keeps track of the packing order internally to make this work scripts can plan ahead for shrinkage by calling pack methods of more important widgets first for instanceon the upcoming tkinter tourwe'll meet code that builds menus and toolbars at the top and bottom of the windowto make sure these are lost last as window is shrunkthey are packed firstbefore the application components in the middle graphical user interfaces
4,969
scroll ( textlistsso that the scroll bars remain as the window shrinks attaching widgets to frames in larger termsthe critical innovation in this example is its use of framesframe widgets are just containers for other widgetsand so give rise to the notion of guis as widget hierarchiesor trees herewin serves as an enclosing window for the other three widgets in generalthoughby attaching widgets to framesand frames to other frameswe can build up arbitrary gui layouts simply divide the user interface into set of increasingly smaller rectanglesimplement each as tkinter frameand attach basic widgets to the frame in the desired screen position in this scriptwhen you specify win in the first argument to the label and button constructorstkinter attaches them to the frame (they become children of the win parentwin itself is attached to the default top-level windowsince we didn' pass parent to the frame constructor when we ask win to run itself (by calling mainloop)tkinter draws all the widgets in the tree we've built the three child widgets also provide pack options nowthe side arguments tell which part of the containing frame ( winto attach the new widget to the label hooks onto the topand the buttons attach to the sides topleftand right are all preassigned string variables imported from tkinter arranging widgets is bit subtler than simply giving sidethoughbut we need to take quick detour into packer geometry management details to see why layoutpacking order and side attachments when widget tree is displayedchild widgets appear inside their parents and are arranged according to their order of packing and their packing options because of thisthe order in which widgets are packed not only gives their clipping orderbut also determines how their side settings play out in the generated display here' how the packer' layout system works the packer starts out with an available space cavity that includes the entire parent container ( the whole frame or top-level window as each widget is packed on sidethat widget is given the entire requested side in the remaining space cavityand the space cavity is shrunk later pack requests are given an entire side of what is leftafter earlier pack requests have shrunk the cavity after widgets are given cavity spaceexpand divides any space leftand fill and anchor stretch and position widgets within their assigned space adding multiple widgets
4,970
button(wintext='hello'command=greetingpack(side=leftlabel(wintext='hello container world'pack(side=topbutton(wintext='quit'command=win quitpack(side=rightyou will wind up with the very different display shown in figure - even though you've moved the label code only one line down in the source file (contrast with figure - figure - packing the label second despite its side settingthe label does not get the entire top of the window nowand you have to think in terms of shrinking cavities to understand why because the hello button is packed firstit is given the entire left side of the frame nextthe label is given the entire top side of what is left finallythe quit button gets the right side of the remainder-- rectangle to the right of the hello button and under the label when this window shrinkswidgets are clipped in reverse order of their packingthe quit button disappears firstfollowed by the label in the original version of this example (figure - )the label spans the entire top side just because it is the first one packednot because of its side option in factif you look at figure - closelyyou'll see that it illustrates the same point--the label appeared between the buttonsbecause they had already carved off the entire left and right sides the packer' expand and fill revisited beyond the effects of packing orderthe fill option we met earlier can be used to stretch the widget to occupy all the space in the cavity side it has been givenand any cavity space left after all packing is evenly allocated among widgets with the expand=yes we saw before for examplecoding this way creates the window in figure - (compare this to figure - )button(wintext='hello'command=greetingpack(side=left,fill=ylabel(wintext='hello container world'pack(side=topbutton(wintext='quit'command=win quitpack(side=rightexpand=yesfill=xtechnicallythe packing steps are just rerun again after window resize but since this means that there won' be enough space left for widgets packed last when the window shrinksit is as if widgets packed first are clipped last graphical user interfaces
4,971
to make all of these grow along with their windowthoughwe also need to make the container frame expandablewidgets expand beyond their initial packer arrangement only if all of their parents expandtoo here are the changes in gui pywin frame(win pack(side=topexpand=yesfill=bothbutton(wintext='hello'command=greetingpack(side=leftfill=ylabel(wintext='hello container world'pack(side=topbutton(wintext='quit'command=win quitpack(side=rightexpand=yes,fill=xwhen this code runsthe frame is assigned the entire top side of its parent as before (that isthe top parcel of the root window)but because it is now marked to expand into unused space in its parent and to fill that space both waysit and all of its attached children expand along with the window figure - shows how figure - gui gets big with an expandable frame using anchor to position instead of stretch and as if that isn' flexible enoughthe packer also allows widgets to be positioned within their allocated space with an anchor optioninstead of filling that space with fill the anchor option accepts tkinter constants identifying all eight points of the compass (nnenwsetc and center as its value ( anchor=nwit instructs the packer to position the widget at the desired position within its allocated spaceif the space allocated for the widget is larger than the space needed to display the widget adding multiple widgets
4,972
side they were givenunless they are positioned with anchor or stretched with fill to demonstratechange gui to use this sort of codebutton(wintext='hello'command=greetingpack(side=leftanchor=nlabel(wintext='hello container world'pack(side=topbutton(wintext='quit'command=win quitpack(side=rightthe only thing new here is that the hello button is anchored to the north side of its space allocation because this button was packed firstit got the entire left side of the parent frame this is more space than is needed to show the buttonso it shows up in the middle of that side by defaultas in figure - ( anchored to the centersetting the anchor to moves it to the top of its sideas shown in figure - figure - anchoring button to the north keep in mind that fill and anchor are applied after widget has been allocated cavity side space by its sidepacking orderand expand extra space request by playing with packing orderssidesfillsand anchorsyou can generate lots of layout and clipping effectsand you should take few moments to experiment with alternatives if you haven' already in the original version of this examplefor instancethe label spans the entire top side just because it is the first packed as we'll see laterframes can be nested in other framestooin order to make more complex layouts in factbecause each parent container is distinct space cavitythis provides sort of escape mechanism for the packer cavity algorithmto better control where set of widgets show upsimply pack them within nested subframe and attach the frame as package to larger container row of push buttonsfor examplemight be easier laid out in frame of its own than if mixed with other widgets in the display directly finallyalso keep in mind that the widget tree created by these examples is really an implicit onetkinter internally records the relationships implied by passed parent widget arguments in oop termsthis is composition relationship--the frame contains label and buttons let' look at inheritance relationships next customizing widgets with classes you don' have to use oop in tkinter scriptsbut it can definitely help as we just sawtkinter guis are built up as class-instance object trees here' another way python' graphical user interfaces
4,973
example - builds the window in figure - example - pp \gui\intro\gui py from tkinter import class hellobutton(button)def __init__(selfparent=none**config)button __init__(selfparent**configself pack(self config(command=self callbackdef callback(self)print('goodbye world 'self quit(add callback method and pack myself could config style too default press action replace in subclasses if __name__ ='__main__'hellobutton(text='hello subclass world'mainloop(figure - button subclass in action this example isn' anything special to look atit just displays single button thatwhen pressedprints message and exits but this timeit is button widget we created on our own the hellobutton class inherits everything from the tkinter button classbut adds callback method and constructor logic to set the command option to self callbacka bound method of the instance when the button is pressed this timethe new widget class' callback methodnot simple functionis invoked the **config argument here is assigned unmatched keyword arguments in dictionaryso they can be passed along to the button constructor the **config in the button constructor call unpacks the dictionary back into keyword arguments (it' actually optional herebecause of the old-style dictionary widget call form we met earlierbut doesn' hurtwe met the config widget method called in hellobutton' constructor earlierit is just an alternative way to pass configuration options after the fact (instead of passing constructor argumentsstandardizing behavior and appearance so what' the point of subclassing widgets like thisin shortit allows sets of widgets made from the customized classes to look and act the same when coded wellwe get both "for freefrom python' oop model this can be powerful technique in larger programs customizing widgets with classes
4,974
example - standardizes behavior--it allows widgets to be configured by subclassing instead of by passing in options in factits hellobutton is true buttonwe can pass in configuration options such as its text as usual when one is made but we can also specify callback handlers by overriding the callback method in subclassesas shown in example - example - pp \gui\intro\gui py from gui import hellobutton class mybutton(hellobutton)subclass hellobutton def callback(self)redefine press-handler method print("ignoring press"if __name__ ='__main__'mybutton(nonetext='hello subclass world'mainloop(this script makes the same windowbut instead of exitingthis mybutton buttonwhen pressedprints to stdout and stays up here is its standard output after being pressed few timesc:\pp \gui\intropython gui py ignoring pressignoring pressignoring pressignoring presswhether it' simpler to customize widgets by subclassing or passing in options is probably matter of taste in this simple example but the larger point to notice is that tk becomes truly object oriented in pythonjust because python is object oriented--we can specialize widget classes using normal class-based and object-oriented techniques in fact this applies to both widget behavior and appearance common appearance for examplealthough we won' study widget configuration options until the next similar customized button class could provide standard look-and-feel different from tkinter' defaults for every instance created from itand approach the notions of "stylesor "themesin some gui toolkitsclass themedbutton(button)config my style too def __init__(selfparent=none**configs)used for each instance button __init__(selfparent**configssee for options self pack(self config(fg='red'bg='black'font=('courier' )relief=raisedbd= themedbutton(text='spam'command=onspamb themedbutton(text='eggs' pack(expand=yesfill=both graphical user interfaces normal button widget objects but same appearance by inheritance
4,975
for complete versionand watch for more on its widget configuration options in but it illustrates the application of common appearance by subclassing widgets directly--every button created from its class looks the sameand will pick up any future changes in its configurations automatically widget subclasses are programmer' toolof coursebut we can also make such configurations accessible to gui' users in larger programs later in the book ( pyeditpyclockand pymailgui)we'll sometimes achieve similar effect by importing configurations from modules and applying them to widgets as they are built if such external settings are used by customized widget subclass like our themedbutton abovethey will again apply to all its instances and subclasses (for referencethe full version of the following code is in file gui -themed-user py)from user_preferences import bcolorbfontbsize get user settings class themedbutton(button)def __init__(selfparent=none**configs)button __init__(selfparent**configsself pack(self config(bg=bcolorfont=(bfontbsize)themedbutton(text='spam'command=onspamthemedbutton(text='eggs'command=oneggsnormal button widget objects all inherit user preferences class mybutton(themedbutton)subclasses inherit prefs too def __init__(selfparent=none**configs)themedbutton __init__(selfparent**configsself config(text='subclass'mybutton(command=onspamagainmore on widget configuration in the next the big picture to take away here is that customizing widget classes with subclasses allows us to tailor both their behavior and their appearance for an entire set of widgets the next example provides yet another way to arrange for specialization--as customizable and attachable widget packagesusually known as components reusable gui components with classes larger gui interfaces are often built up as subclasses of framewith callback handlers implemented as methods this structure gives us natural place to store information between eventsinstance attributes record state it also allows us to both specialize guis by overriding their methods in new subclasses and attach them to larger gui structures to reuse them as general components for instancea gui text editor implemented as frame subclass can be attached to and configured by any number of other guisif done wellwe can plug such text editor into any user interface that needs text editing tools reusable gui components with classes
4,976
figure - example - pp \gui\intro\gui py from tkinter import class hello(frame)def __init__(selfparent=none)frame __init__(selfparentself pack(self data self make_widgets(an extended frame do superclass init attach widgets to self def make_widgets(self)widget button(selftext='hello frame world!'command=self messagewidget pack(side=leftdef message(self)self data + print('hello frame world % !self dataif __name__ ='__main__'hello(mainloop(figure - custom frame in action this example pops up single-button window when pressedthe button triggers the self message bound method to print to stdout again here is the output after pressing this button four timesnotice how self data ( simple counter hereretains its state between pressesc:\pp \gui\intropython gui py hello frame world hello frame world hello frame world hello frame world this may seem like roundabout way to show button (we did it in fewer lines in examples - - and - but the hello class provides an enclosing organizational structure for building guis in the examples prior to the last sectionwe made guis using function-like approachwe called widget constructors as though they were functions and hooked widgets together manually by passing in parents to widget construction calls there was no notion of an enclosing contextapart from the global graphical user interfaces
4,977
can make for brittle code when building up larger gui structures but by subclassing frame as we've done herethe class becomes an enclosing context for the guiwidgets are added by attaching objects to selfan instance of frame container subclass ( buttoncallback handlers are registered as bound methods of selfand so are routed back to code in the class ( self messagestate information is retained between events by assigning to attributes of selfvisible to all callback methods in the class ( self datait' easy to make multiple copies of such gui componenteven within the same processbecause each class instance is distinct namespace classes naturally support customization by inheritance and by composition attachment in senseentire guis become specialized frame objects with extensions for an application classes can also provide protocols for building widgets ( the make_widgets method here)handle standard configuration chores (like setting window manager options)and so on in shortframe subclasses provide simple way to organize collections of other widget-class objects attaching class components perhaps more importantlysubclasses of frame are true widgetsthey can be further extended and customized by subclassing and can be attached to enclosing widgets for instanceto attach the entire package of widgets that class builds to something elsesimply create an instance of the class with real parent widget passed in to illustraterunning the script in example - creates the window shown in figure - example - pp \gui\intro\gui py from sys import exit from tkinter import from gui import hello parent frame(noneparent pack(hello(parentpack(side=rightget tk widget classes get the subframe class make container widget attach hello instead of running it button(parenttext='attach'command=exitpack(side=leftparent mainloop(reusable gui components with classes
4,978
this script just adds hello' button to the right side of parent-- container frame in factthe button on the right in this window represents an embedded componentits button really represents an attached python class object pressing the embedded class' button on the right prints message as beforepressing the new button exits the gui by sys exit callc:\pp \gui\intropython gui py hello frame world hello frame world hello frame world hello frame world in more complex guiswe might instead attach large frame subclasses to other container components and develop each independently for instanceexample - is yet another specialized frame itselfbut it attaches an instance of the original hello class in more object-oriented fashion when run as top-level programit creates window identical to the one shown in figure - example - pp \gui\intro\gui py from tkinter import from gui import hello get tk widget classes get the subframe class class hellocontainer(frame)def __init__(selfparent=none)frame __init__(selfparentself pack(self makewidgets(def makewidgets(self)hello(selfpack(side=rightattach hello to me button(selftext='attach'command=self quitpack(side=leftif __name__ ='__main__'hellocontainer(mainloop(this looks and works exactly like gui but registers the added button' callback handler as self quitwhich is just the standard quit widget method this class inherits from frame the window this time represents two python classes at work--the embedded component' widgets on the right (the original hello buttonand the container' widgets on the left naturallythis is simple example (we attached only single button hereafter allbut in more practical user interfacesthe set of widget class objects attached in this way graphical user interfaces
4,979
attach an already coded and fully debugged calculator objectyou'll begin to better understand the power of this paradigm if we code all of our gui components as classesthey automatically become library of reusable widgetswhich we can combine in other applications as often as we like extending class components when guis are built with classesthere are variety of ways to reuse their code in other displays to extend hello instead of attaching itwe just override some of its methods in new subclass (which itself becomes specialized frame widgetthis technique is shown in example - example - pp \gui\intro\gui py from tkinter import from gui import hello class helloextender(hello)def make_widgets(self)extend method here hello make_widgets(selfbutton(selftext='extend'command=self quitpack(side=rightdef message(self)print('hello'self dataredefine method here if __name__ ='__main__'helloextender(mainloop(this subclass' make_widgets method here first builds the superclass' widgets and then adds second extend button on the rightas shown in figure - figure - customized class' widgetson the left because it redefines the message methodpressing the original superclass' button on the left now prints different string to stdout (when searching up from selfthe message attribute is found first in this subclassnot in the superclass) :\pp \gui\intropython gui py hello hello hello hello but pressing the new extend button on the rightwhich is added by this subclassexits immediatelysince the quit method (inherited from hellowhich inherits it from reusable gui components with classes
4,980
the original to add new button and change message' behavior although this example is simpleit demonstrates technique that can be powerful in practiceto change gui' behaviorwe can write new class that customizes its parts rather than changing the existing gui code in place the main code need be debugged only once and can be customized with subclasses as unique needs arise the moral of this story is that tkinter guis can be coded without ever writing single new classbut using classes to structure your gui code makes it much more reusable in the long run if done wellyou can both attach already debugged components to new interfaces and specialize their behavior in new external subclasses as needed for custom requirements either waythe initial upfront investment to use classes is bound to save coding time in the end standalone container classes before we move oni want to point out that it' possible to reap most of the class-based component benefits previously mentioned by creating standalone classes not derived from tkinter frames or other widgets for instancethe class in example - generates the window shown in figure - example - pp \gui\intro\gui py from tkinter import class hellopackagedef __init__(selfparent=none)self top frame(parentself top pack(self data self make_widgets(not widget subbclass embed frame attach widgets to self top def make_widgets(self)button(self toptext='bye'command=self top quitpack(side=leftbutton(self toptext='hye'command=self messagepack(side=rightdef message(self)self data + print('hello number'self dataif __name__ ='__main__'hellopackage(top mainloop(figure - standalone class package in action graphical user interfaces
4,981
the guimuch as beforec:\pp \gui\intropython gui py hello number hello number hello number hello number also as beforeself data retains state between eventsand callbacks are routed to the self message method within this class unlike beforethe hellopackage class is not itself kind of frame widget in factit' not kind of anything--it serves only as generator of namespaces for storing away real widget objects and state because of thatwidgets are attached to self top (an embedded frame)not to self moreoverall references to the object as widget must descend to the embedded frameas in the top main loop call to start the gui at the end of the script this makes for bit more coding within the classbut it avoids potential name clashes with both attributes added to self by the tkinter framework and existing tkinter widget methods for instanceif you define config method in your classit will hide the config call exported by tkinter with the standalone class package in this exampleyou get only the methods and instance attributes that your class defines in practicetkinter doesn' use very many namesso this is not generally big concern +it can happenof coursebut franklyi've never seen real tkinter name clash in widget subclasses in some years of python coding moreoverusing standalone classes is not without other downsides although they can generally be attached and subclassed as beforethey are not quite plug-and-play compatible with real widget objects for instancethe configuration calls made in example - for the frame subclass fail in example - example - pp \gui\intro\gui py from tkinter import from gui import hellopackage or get from gui --__getattr__ added frm frame(frm pack(label(frmtext='hello'pack(part hellopackage(frm+if you study the tkinter module' source code (todaymostly in file __init__ py in lib\tkinter)you'll notice that many of the attribute names it creates start with single underscore to make them unique from yoursothers do not because they are potentially useful outside of the tkinter implementation ( self masterself childrencuriouslyat this writing most of tkinter still does not use the python "pseudoprivate attributestrick of prefixing attribute names with two leading underscores to automatically add the enclosing class' name and thus localize them to the creating class if tkinter is ever rewritten to employ this featurename clashes will be much less likely in widget subclasses most of the attributes of widget classesthoughare methods intended for use in client scriptsthe single underscore names are accessible toobut are less likely to clash with most names of your own reusable gui components with classes
4,982
frm mainloop(fails!--need part top pack(side=rightthis won' quite workbecause part isn' really widget to treat it as suchyou must descend to part top before making gui configurations and hope that the name top is never changed by the class' developer in other wordsit exposes some of the class' internals the class could make this better by defining method that always routes unknown attribute fetches to the embedded frameas in example - example - pp \gui\intro\gui py import gui from tkinter import class hellopackage(gui hellopackage)def __getattr__(selfname)return getattr(self topnamepass off to real widget if __name__ ='__main__'hellopackage(mainloop(invokes __getattr__as isthis script simply creates figure - againchanging example - to import this extended hellopackage from gui cthoughproduces the correctly-working window in figure - figure - standalone class package in action routing attribute fetches to nested widgets works this waybut that then requires even more extra coding in standalone package classes as usualthoughthe significance of all these trade-offs varies per application the end of the tutorial in this we learned the core concepts of python/tkinter programming and met handful of simple widget objects along the way-- labelsbuttonsframesand the packer geometry manager we've seen enough to construct simple interfacesbut we have really only scratched the surface of the tkinter widget set in the next two we will apply what we've learned here to study the rest of the tkinter libraryand we'll learn how to use it to generate the kinds of interfaces you expect to see in realistic gui programs as preview and roadmaptable - lists the kinds of widgets we'll meet there in roughly their order of appearance note that this graphical user interfaces
4,983
table - tkinter widget classes widget class description label simple message area button simple labeled push-button widget frame container for attaching and arranging other widget objects topleveltk new window managed by the window manager message multiline label entry simple single-line text-entry field checkbutton two-state button widgettypically used for multiple-choice selections radiobutton two-state button widgettypically used for single-choice selections scale slider widget with scalable positions photoimage an image object used for displaying full-color images on other widgets bitmapimage an image object used for displaying bitmap images on other widgets menu set of options associated with menubutton or top-level window menubutton button that opens menu of selectable options and submenus scrollbar control for scrolling other widgets ( listboxcanvastextlistbox list of selection names text multiline text browse/edit widgetwith support for fontsand so on canvas graphic drawing areawhich supports linescirclesphotostextand so on we've already met labelbuttonand frame in this tutorial to make the remaining topics easier to absorbthey are split over the next two covers the first widgets in this table up to but not including menuand presents widgets that are lower in this table besides the widget classes in this tablethere are additional classes and tools in the tkinter librarymany of which we'll explore in the following two as wellgeometry management packgridplace tkinter linked variables stringvarintvardoublevarbooleanvar advanced tk widgets spinboxlabelframepanedwindow composite widgets dialogscrolledtextoptionmenu the end of the tutorial
4,984
widget afterwaitand update methods other tools standard dialogsclipboardbind and eventwidget configuration optionscustom and modal dialogsanimation techniques most tkinter widgets are familiar user interface devices some are remarkably rich in functionality for instancethe text class implements sophisticated multiline text widget that supports fontscolorsand special effects and is powerful enough to implement web browser' page display the similarly feature-rich canvas class provides extensive drawing tools powerful enough for visualization and other image-processing applications beyond thistkinter extensions such as the pmwtixand ttk packages described at the start of this add even richer widgets to gui programmer' toolbox python/tkinter for tcl/tk converts at the start of this mentioned that tkinter is python' interface to the tk gui libraryoriginally written for the tcl language to help readers migrating from tcl to python and to summarize some of the main topics we met in this this section contrasts python' tk interface with tcl' this mapping also helps make tk references written for other languages more useful to python developers in general termstcl' command-string view of the world differs widely from python' object-based approach to programming in terms of tk programmingthoughthe syntactic differences are fairly small here are some of the main distinctions in python' tkinter interfacecreation widgets are created as class instance objects by calling widget class masters (parentsparents are previously created objects that are passed to widget-class constructors widget options options are constructor or config keyword arguments or indexed keys operations widget operations (actionsbecome tkinter widget class object methods callbacks callback handlers are any callable objectsfunctionmethodlambdaand so on extension widgets are extended using python class inheritance mechanisms composition interfaces are constructed by attaching objectsnot by concatenating names graphical user interfaces
4,985
variables associated with widgets are tkinter class objects with methods in pythonwidget creation commands ( buttonare python class names that start with an uppercase letter ( button)two-word widget operations ( add commandbecome single method name with an underscore ( add_command)and the "configuremethod can be abbreviated as "config,as in tcl in we will also see that tkinter "variablesassociated with widgets take the form of class instance objects ( stringvarintvarwith get and set methodsnot simple python or tcl variable names table - shows some of the primary language mappings in more concrete terms table - tk-to-tkinter mappings operation tcl/tk python/tkinter creation frame panel panel frame(masters button panel quit quit button(paneloptions button panel go -fg black go button(panelfg='black'configure panel go config -bg red go config(bg='red'go['bg''redactions popup invoke popup invoke(packing pack panel -side left -fill panel pack(side=leftfill=xsome of these differences are more than just syntacticof course for instancepython builds an internal widget object tree based on parent arguments passed to widget constructorswithout ever requiring concatenated widget pathname strings once you've made widget objectyou can use it directly by object reference tcl coders can hide some dotted pathnames by manually storing them in variablesbut that' not quite the same as python' purely object-based model once you've written few python/tkinter scriptsthoughthe coding distinctions in the python object world will probably seem trivial at the same timepython' support for object-oriented techniques adds an entirely new component to tk developmentyou get the same widgetsplus python' support for code structure and reuse python/tkinter for tcl/tk converts
4,986
tkinter tourpart "widgets and gadgets and guisoh my!this is continuation of our look at gui programming in python the previous used simple widgets--buttonslabelsand the like--to demonstrate the fundamentals of python/tkinter coding that was simple by designit' easier to grasp the big gui picture if widget interface details don' get in the way but now that we've seen the basicsthis and the next move on to present tour of more advanced widget objects and tools available in the tkinter library as we'll findthis is where gui scripting starts getting both practical and fun in these two we'll meet classes that build the interface devices you expect to see in real programs-- sliderscheck buttonsmenusscrolled listsdialogsgraphicsand so on after these the last gui moves on to present larger guis that utilize the coding techniques and the interfaces shown in all prior gui in these two thoughexamples are small and self-contained so that we can focus on widget details this topics technicallywe've already used handful of simple widgets in so far we've met labelbuttonframeand tkand studied pack geometry management concepts along the way although all of these are basicthey represent tkinter interfaces in general and can be workhorses in typical guis frame containersfor instanceare the basis of hierarchical display layout in this and the following we'll explore additional options for widgets we've already seen and move beyond the basics to cover the rest of the tkinter widget set here are some of the widgets and topics we'll explore in this toplevel and tk widgets message and entry widgets checkbuttonradiobuttonand scale widgets
4,987
widget and window configuration options dialogsboth standard and custom low-level event binding tkinter linked variable objects using the python imaging library (pilextension for other image types and operations after this concludes the two-part tour by presenting the remainder of the tkinter library' tool setmenustextcanvasesanimationand more to make this tour interestingi'll also introduce few notions of component reuse along the way for instancesome later examples will be built using components written for prior examples although these two tour introduce widget interfacesthis book is also about python programming in generalas we'll seetkinter programming in python can be much more than simply drawing circles and arrows configuring widget appearance so farall the buttons and labels in examples have been rendered with default lookand-feel that is standard for the underlying platform with my machine' color schemethat usually means that they're gray on windows tkinter widgets can be made to look arbitrarily differentthoughusing handful of widget and packer options because generally can' resist the temptation to customize widgets in examplesi want to cover this topic early on the tour example - introduces some of the configuration options available in tkinter example - pp \gui\tour\config-label py from tkinter import root tk(labelfont ('times' 'bold'widget label(roottext='hello config world'widget config(bg='black'fg='yellow'widget config(font=labelfontwidget config(height= width= widget pack(expand=yesfill=bothroot mainloop(familysizestyle yellow text on black label use larger font initial sizelines,chars rememberwe can call widget' config method to reset its options at any timeinstead of passing all of them to the object' constructor herewe use it to set options that produce the window in figure - this may not be completely obvious unless you run this script on real computer (alasi can' show it in color here)but the label' text shows up in yellow on black tkinter tourpart
4,988
backgroundand with font that' very different from what we've seen so far in factthis script customizes the label in number of wayscolor by setting the bg option of the label widget hereits background is displayed in blackthe fg option similarly changes the foreground (textcolor of the widget to yellow these color options work on most tkinter widgets and accept either simple color name ( 'blue'or hexadecimal string most of the color names you are familiar with are supported (unless you happen to work for crayolayou can also pass hexadecimal color identifier string to these options to be more specificthey start with and name color by its redgreenand blue saturationswith an equal number of bits in the string for each for instance'#ff specifies eight bits per color and defines pure red"fmeans four " bits in hexadecimal we'll come back to this hex form when we meet the color selection dialog later in this size the label is given preset size in lines high and characters wide by setting its height and width attributes you can use this setting to make the widget larger than the tkinter geometry manager would by default font this script specifies custom font for the label' text by setting the label' font attribute to three-item tuple giving the font familysizeand style (heretimes -pointand boldfont style can be normalboldromanitalicunderlineover strikeor combinations of these ( "bold italic"tkinter guarantees that timescourierand helvetica font family names exist on all platformsbut others may worktoo ( system gives the system font on windowsfont settings like this work on all widgets with textsuch as labelsbuttonsentry fieldslistboxesand text (the latter of which can even display more than one font at once with "tags"the font option still accepts older -windows-style font indicators--long strings with dashes and stars--but the newer tuple font indicator form is more platform independent configuring widget appearance
4,989
finallythe label is made generally expandable and stretched by setting the pack expand and fill options we met in the last the label grows as the window does if you maximize this windowits black background fills the whole screen and the yellow message is centered in the middletry it in this scriptthe net effect of all these settings is that this label looks radically different from the ones we've been making so far it no longer follows the windows standard look-and-feelbut such conformance isn' always important for referencetkinter provides additional ways to customize appearance that are not used by this scriptbut which may appear in othersborder and relief bdn widget option can be used to set border widthand reliefs option can specify border styles can be flatsunkenraisedgroovesolidor ridge--all constants exported by the tkinter module cursor cursor option can be given to change the appearance of the mouse pointer when it moves over the widget for instancecursor='gumbychanges the pointer to gumby figure (the green kindother common cursor names used in this book include watchpencilcrossand hand state some widgets also support the notion of statewhich impacts their appearance for examplea state=disabled option will generally stipple (gray outa widget on screen and make it unresponsivenormal does not some widgets support readonly state as wellwhich displays normally but is unresponsive to changes padding extra space can be added around many widgets ( buttonslabelsand textwith the padxn and padyn options interestinglyyou can set these options both in pack calls (where it adds empty space around the widget in generaland in widget object itself (where it makes the widget largerto illustrate some of these extra settingsexample - configures the custom button captured in figure - and changes the mouse pointer when it is positioned above it example - pp \gui\tour\config-button py from tkinter import widget button(text='spam'padx= pady= widget pack(padx= pady= widget config(cursor='gumby'widget config(bd= relief=raisedwidget config(bg='dark green'fg='white'widget config(font=('helvetica' 'underline italic')mainloop( tkinter tourpart
4,990
to see the effects generated by these two scriptssettingstry out few changes on your computer most widgets can be given custom appearance in the same wayand we'll see such options used repeatedly in this text we'll also meet operational configurationssuch as focus (for focusing inputand others in factwidgets can have dozens of optionsmost have reasonable defaults that produce native look-and-feel on each windowing platformand this is one reason for tkinter' simplicity but tkinter lets you build more custom displays when you want to for more on ways to apply configuration options to provide common look-and-feel for your widgetsrefer back to "customizing widgets with classeson page especially its themedbutton examples now that you know more about configurationits examplessource code should more readily show how configurations applied in widget subclasses are automatically inherited by all instances and subclasses the new ttk extension described in also provides additional ways to configure widgets with its notion of themessee the preceding for more details and resources on ttk top-level windows tkinter guis always have an application root windowwhether you get it by default or create it explicitly by calling the tk object constructor this main root window is the one that opens when your program runsand it is where you generally pack your most important and long-lived widgets in additiontkinter scripts can create any number of independent windowsgenerated and popped up on demandby creating toplevel widget objects each toplevel object created produces new window on the display and automatically adds it to the program' gui event-loop processing stream (you don' need to call the mainloop method of new windows to activate themexample - builds root and two pop-up windows top-level windows
4,991
import sys from tkinter import toplevelbuttonlabel win toplevel(win toplevel(two independent windows but part of same process button(win text='spam'command=sys exitpack(button(win text='spam'command=sys exitpack(label(text='popups'pack(win mainloop(on default tk(root window the toplevel script gets root window by default (that' what the label is attached tosince it doesn' specify real parent)but it also creates two standalone toplevel windows that appear and function independently of the root windowas seen in figure - figure - two toplevel windows and root window the two toplevel windows on the right are full-fledged windowsthey can be independently iconifiedmaximizedand so on toplevels are typically used to implement multiple-window displays and pop-up modal and nonmodal dialogs (more on dialogs in the next sectionthey stay up until they are explicitly destroyed or until the application that created them exits in factas coded herepressing the in the upper right corner of either of the toplevel windows kills that window only on the other handthe entire program and all it remaining windows are closed if you press either of the created buttons or the main window' (more on shutdown protocols in momentit' important to know that although toplevels are independently active windowsthey are not separate processesif your program exitsall of its windows are erasedincluding all toplevel windows it may have created we'll learn how to work around this rule later by launching independent gui programs tkinter tourpart
4,992
toplevel is roughly like frame that is split off into its own window and has additional methods that allow you to deal with top-level window properties the tk widget is roughly like toplevelbut it is used to represent the application root window toplevel windows have parentsbut tk windows do not--they are the true roots of the widget hierarchies we build when making tkinter guis we got tk root for free in example - because the label had default parentdesignated by not having widget in the first argument of its constructor calllabel(text='popups'pack(on default tk(root window passing none to widget constructor' first argument (or to its master keyword argumenthas the same default-parent effect in other scriptswe've made the tk root more explicit by creating it directlylike thisroot tk(label(roottext='popups'pack(root mainloop(on explicit tk(root window in factbecause tkinter guis are hierarchyby default you always get at least one tk root windowwhether it is named explicitlyas hereor not though not typicalthere may be more than one tk root if you make them manuallyand program ends if all its tk windows are closed the first tk top-level window created--whether explicitly by your codeor automatically by python when needed--is used as the default parent window of widgets and other windows if no parent is provided you should generally use the tk root window to display top-level information of some sort if you don' attach widgets to the rootit may show up as an odd empty window when you run your script (often because you used the default parent unintentionally in your code by omitting widget' parent and didn' pack widgets attached to ittechnicallyyou can suppress the default root creation logic and make multiple root windows with the tk widgetas in example - example - pp \gui\tour\toplevel py import tkinter from tkinter import tkbutton tkinter nodefaultroot(win tk(win tk(two independent root windows button(win text='spam'command=win destroypack(button(win text='spam'command=win destroypack(win mainloop(when runthis script displays the two pop-up windows of the screenshot in figure - only (there is no third root windowbut it' more common to use the tk root as main window and create toplevel widgets for an application' pop-up windows top-level windows
4,993
windowinstead of sys exit to shut down the entire programto see how this method really does its worklet' move on to window protocols top-level window protocols both tk and toplevel widgets export extra methods and features tailored for their toplevel roleas illustrated in example - example - pp \gui\tour\toplevel py ""pop up three new windowswith style destroy(kills one windowquit(kills all windows and app (ends mainloop)top-level windows have titleiconiconify/deiconify and protocol for wm eventsthere always is an application root windowwhether by default or created as an explicit tk(objectall top-level windows are containersbut they are never packed/griddedtoplevel is like framebut new windowand can have menu""from tkinter import root tk(explicit root trees [('the larch!''light blue')('the pine!''light green')('the giant redwood!''red')for (treecolorin treeswin toplevel(rootwin title('sing 'win protocol('wm_delete_window'lambda:nonewin iconbitmap('py-blue-trans-out ico'new window set border ignore close not red tk msg button(wintext=treecommand=win destroykills one win msg pack(expand=yesfill=bothmsg config(padx= pady= bd= relief=raisedmsg config(bg='black'fg=colorfont=('times' 'bold italic')root title('lumberjack demo'label(roottext='main window'width= pack(button(roottext='quit all'command=root quitpack(root mainloop(kills all app this program adds widgets to the tk root windowimmediately pops up three toplevel windows with attached buttonsand uses special top-level protocols when runit generates the scene captured in living black-and-white in figure - (the buttonstext shows up bluegreenand red on color display tkinter tourpart
4,994
there are few operational details worth noticing hereall of which are more obvious if you run this script on your machineintercepting closesprotocol because the window manager close event has been intercepted by this script using the top-level widget protocol methodpressing the in the top-right corner doesn' do anything in the three toplevel pop ups the name string wm_delete_window identifies the close operation you can use this interface to disallow closes apart from the widgets your script creates the function created by this script' lambda:none does nothing but return none killing one window (and its children)destroy pressing the big black buttons in any one of the three pop ups kills that pop up onlybecause the pop up runs the widget destroy method the other windows live onmuch as you would expect of pop-up dialog window technicallythis call destroys the subject widget and any other widgets for which it is parent for windowsthis includes all their content for simpler widgetsthe widget is erased because toplevel windows have parentstootheir relationships might matter on destroy--destroying windoweven the automatic or first-made tk root which is used as the default parentalso destroys all its child windows since tk root windows have no parentsthey are unaffected by destroys of other windows moreoverdestroying the last tk root window remaining (or the only tk root createdeffectively ends the program toplevel windowshoweverare always destroyed with their parentsand their destruction doesn' impact other windows to which they are not ancestors this makes them ideal for pop-up dialogs technicallya toplevel can be child of any type of widget and will be destroyed with itthough they are usually children of an automatic or explicit tk top-level windows
4,995
to kill all the windows at once and end the gui application (reallyits active mainloop call)the root window' button runs the quit method instead that ispressing the root window' button ends the program in generalthe quit method immediately ends the entire application and closes all its windows it can be called through any tkinter widgetnot just through the top-level windowit' also available on framesbuttonsand so on see the discussion of the bind method and its events later in this for more on quit and destroy window titlestitle as introduced in top-level window widgets (tk and toplevelhave title method that lets you change the text displayed on the top border herethe window title text is set to the string 'sing in the pop-ups to override the default 'tkwindow iconsiconbitmap the iconbitmap method changes top-level window' icon it accepts an icon or bitmap file and uses it for the window' icon graphic when it is both minimized and open on windowspass in the name of ico file (this example uses one in the current directory)it will replace the default red "tkicon that normally appears in the upper-lefthand corner of the window as well as in the windows taskbar on other platformsyou may need to use other icon file conventions if the icon calls in this book won' work for you (or simply comment-out the calls altogether if they cause scripts to fail)icons tend to be platform-specific feature that is dependent upon the underlying window manager geometry management top-level windows are containers for other widgetsmuch like standalone frame unlike framesthoughtop-level window widgets are never themselves packed (or griddedor placedto embed widgetsthis script passes its windows as parent arguments to label and button constructors it is also possible to fetch the maximum window size (the physical screen display sizeas [widthheighttuplewith the maxsize(methodas well as set the initial size of window with the top-level geometry(width height "method it is generally easier and more user-friendly to let tkinter (or your userswork out window size for youbut display size may be used for tasks such as scaling images (see the discussion on pyphoto in for an examplein additiontop-level window widgets support other kinds of protocols that we will utilize later on in this tourstate the iconify and withdraw top-level window object methods allow scripts to hide and erase window on the flydeiconify redraws hidden or erased window the state method queries or changes window' statevalid states passed in or returned include iconicwithdrawnzoomed (full screen on windowsuse geometry tkinter tourpart
4,996
lower raise and lower window with respect to its siblings (lift is the tk raise commandbut avoids python reserved wordsee the alarm scripts near the end of for usage menus each top-level window can have its own window menus tooboth the tk and the toplevel widgets have menu option used to associate horizontal menu bar of pull-down option lists this menu bar looks as it should on each platform on which your scripts are run we'll explore menus early in most top-level window-manager-related methods can also be named with "wm_at the frontfor instancestate and protocol can also be called wm_state and wm_protocol notice that the script in example - passes its toplevel constructor calls an explicit parent widget--the tk root window (that istoplevel(root)toplevels can be associated with parent just as other widgets caneven though they are not visually embedded in their parents coded the script this way to avoid what seems like an odd featureif coded instead like thiswin toplevel(new window and if no tk root yet existsthis call actually generates default tk root window to serve as the toplevel' parentjust like any other widget call without parent argument the problem is that this makes the position of the following line crucialroot tk(explicit root if this line shows up above the toplevel callsit creates the single root window as expected but if you move this line below the toplevel callstkinter creates default tk root window that is different from the one created by the script' explicit tk call you wind up with two tk roots just as in example - move the tk call below the toplevel calls and rerun it to see what mean you'll get fourth window that is completely emptyas rule of thumbto avoid such odditiesmake your tk root windows early on and make them explicit all of the top-level protocol interfaces are available only on top-level window widgetsbut you can often access them by going through other widgetsmaster attributes--links to the widget parents for exampleto set the title of window in which frame is containedsay something like thistheframe master title('spam demo'master is the container window naturallyyou should do so only if you're sure that the frame will be used in only one kind of window general-purpose attachable components coded as classesfor instanceshould leave window property settings to their client applications top-level widgets have additional toolssome of which we may not meet in this book for instanceunder unix window managersyou can also set the name used on the window' icon (iconnamebecause some icon options may be useful when scripts run top-level windows
4,997
nowthe next scheduled stop on this tour explores one of the more common uses of top-level windows dialogs dialogs are windows popped up by script to provide or request additional information they come in two flavorsmodal and nonmodalmodal these dialogs block the rest of the interface until the dialog window is dismissedusers must reply to the dialog before the program continues nonmodal these dialogs can remain on-screen indefinitely without interfering with other windows in the interfacethey can usually accept inputs at any time regardless of their modalitydialogs are generally implemented with the toplevel window object we met in the prior sectionwhether you make the toplevel or not there are essentially three ways to present pop-up dialogs to users with tkinter--by using common dialog callsby using the now-dated dialog objectand by creating custom dialog windows with toplevels and other kinds of widgets let' explore the basics of all three schemes standard (commondialogs because standard dialog calls are simplerlet' start here first tkinter comes with collection of precoded dialog windows that implement many of the most common pop ups programs generate--file selection dialogserror and warning pop upsand question and answer prompts they are called standard dialogs (and sometimes common dialogsbecause they are part of the tkinter libraryand they use platform-specific library calls to look like they should on each platform tkinter file open dialogfor instancelooks like any other on windows all standard dialog calls are modal (they don' return until the dialog box is dismissed by the user)and they block the program' main window while they are displayed scripts can customize these dialogswindows by passing message texttitlesand the like since they are so simple to uselet' jump right into example - (coded as pyw file here to avoid shell pop up when clicked in windowsexample - pp \gui\tour\dlg pyw from tkinter import from tkinter messagebox import def callback()if askyesno('verify''do you really want to quit?')showwarning('yes''quit not yet implemented' tkinter tourpart
4,998
showinfo('no''quit has been cancelled'errmsg 'sorryno spam allowed!button(text='quit'command=callbackpack(fill=xbutton(text='spam'command=(lambdashowerror('spam'errmsg))pack(fill=xmainloop( lambda anonymous function is used here to wrap the call to showerror so that it is passed two hardcoded arguments (rememberbutton-press callbacks get no arguments from tkinter itselfwhen runthis script creates the main window in figure - figure - dlg main windowbuttons to trigger pop ups when you press this window' quit buttonthe dialog in figure - is popped up by calling the standard askyesno function in the tkinter package' messagebox module this looks different on unix and macintosh systemsbut it looks like you' expect when run on windows (and in fact varies its appearance even across different versions and configurations of windows--using my default window setupit looks slightly different than it did on windows xp in the prior editionthe dialog in figure - blocks the program until the user clicks one of its buttonsif the dialog' yes button is clicked (or the enter key is pressed)the dialog call returns with true value and the script pops up the standard dialog in figure - by calling showwarning figure - dlg askyesno dialog (windows dialogs
4,999
there is nothing the user can do with figure - ' dialog but press ok if no is clicked in figure - ' quit verification dialoga showinfo call creates the pop up in figure - instead finallyif the spam button is clicked in the main windowthe standard dialog captured in figure - is generated with the standard showerror call figure - dlg showinfo dialog figure - dlg showerror dialog all of this makes for lot of window pop upsof courseand you need to be careful not to rely on these dialogs too much (it' generally better to use input fields in long-lived tkinter tourpart