id
int64
0
25.6k
text
stringlengths
0
4.59k
5,100
write('% dall work and no play makes jack dull boy \nif close( :\pp \gui\tourpython makefile py :\pp \gui\tourpython scrolledtext py jack txt pp scrolledtext to view filepass its name on the command line--its text is automatically displayed in the new window by defaultit is shown in font that may vary per platform (and might not be fixed-width on some)but we'll pass font option to the text widget in the next example to change that pressing the escape key fetches and displays the full text content of the widget as single string (more on this in momentnotice the pp scrolledtext message printed when this script runs because there is also scrolledtext py file in the standard python distribution (in module tkinter scrolledtextwith very different implementation and interfacethe one here identifies itself when run or importedso you can tell which one you've got if the standard library' alternative ever goes awayimport the class listed to get simple text browserand adjust any text widget configuration calls to include text qualifier level ( text config instead of configthe library version subclasses text directlynot frameprogramming the text widget to understand how this script works at allthoughwe have to detour into few text widget details here earlier we met the entry and message widgetswhich address subset of the text widget' uses the text widget is much richer in both features and interfaces--it supports both input and display of multiple lines of textediting operations for both programs and interactive usersmultiple fonts and colorsand much more text objects are createdconfiguredand packed just like any other widgetbut they have properties all their own text is python string although the text widget is powerful toolits interface seems to boil down to two core concepts firstthe content of text widget is represented as string in python scriptsand multiple lines are separated with the normal \ line terminator the string 'words\ngo here'for instancerepresents two lines when stored in or fetched from text widgetit would normally have trailing \ alsobut it doesn' have to to help illustrate this pointthis script binds the escape key press to fetch and print the entire contents of the text widget it embedsc:\pp \gui\tourpython scrolledtext py pp scrolledtext 'words\ngo here'always look\non the bright\nside of life\ tkinter tourpart
5,101
run without argumentsthe script stuffs simple literal string into the widgetdisplayed by the first escape press output here (recall that \ is the escape sequence for the lineend characterthe second output here happens after editing the window' textwhen pressing escape in the shrunken window captured in figure - by defaulttext widget text is fully editable using the usual edit operations for your platform figure - scrolledtext gets positive outlook string positions the second key to understanding text code has to do with the ways you specify position in the text string like the listboxtext widgets allow you to specify such position in variety of ways in textmethods that expect position to be passed in will accept an indexa markor tag reference moreoversome special operations are invoked with predefined marks and tags--the insert cursor is mark insertand the current selection is tag sel since they are fundamental to text and the source of much of its expressive powerlet' take closer look at these settings text indexes because it is multiple-line widgettext indexes identify both line and column for instanceconsider the interfaces of the basic insertdeleteand fetch text operations used by this scriptself text insert(' 'textself text delete(' 'endreturn self text get(' 'end+'- 'insert text at the start delete all current text fetch first through last in all of thesethe first argument is an absolute index that refers to the start of the text stringstring ' means row column (rows are numbered from and columns from though ' is accepted as reference to the start of the texttooan index ' refers to the second character in the second row like the listboxtext indexes can also be symbolic namesthe end in the preceding delete call refers to the position just past the last character in the text string (it' tkinter variable preset to string 'end'similarlythe symbolic index insert (reallystring 'insert'refers to the position immediately after the insert cursor--the place where characters would appear if typed at the keyboard symbolic names such as insert can also be called marksdescribed in moment text
5,102
index expression end+'- cin the get call in the previous examplefor instanceis really the string 'end- cand refers to one character back from end because end points to just beyond the last character in the text stringthis expression refers to the last character itself the - extension effectively strips the trailing \ that this widget adds to its contents (and which may add blank line if saved in filesimilar index string extensions let you name characters ahead (+ )name lines ahead and behind (+ - )and specify things such as line ends and word starts around an index (lineendwordstartindexes show up in most text widget calls text marks besides row/column identifier stringsyou can also pass positions as names of marks--symbolic names for position between two characters unlike absolute rowcolumn positionsmarks are virtual locations that move as new text is inserted or deleted (by your script or your usera mark always refers to its original locationeven if that location shifts to different row and column over time to create markcall the text object' mark_set method with string name and an index to give its logical location for instancethis script sets the insert cursor at the start of the text initiallywith call like the first one hereself text mark_set(insert' 'self text mark_set('linetwo'' 'set insert cursor to start mark current line the name insert is predefined special mark that identifies the insert cursor positionsetting it changes the insert cursor' location to make mark of your ownsimply provide unique name as in the second call here and use it anywhere you need to specify text position the mark_unset call deletes marks by name text tags in addition to absolute indexes and symbolic mark namesthe text widget supports the notion of tags--symbolic names associated with one or more substrings within the text widget' string tags can be used for many thingsbut they also serve to represent position anywhere you need onetagged items are named by their beginning and ending indexeswhich can be later passed to position-based calls for exampletkinter provides built-in tag namesel-- tkinter name preassigned to string 'sel'--which automatically refers to currently selected text to fetch the text selected (highlightedwith mouserun either of these callstext self text get(sel_firstsel_lasttext self text get('sel first''sel last'use tags for from/to indexes strings and constants work the names sel_first and sel_last are just preassigned variables in the tkinter module that refer to the strings used in the second line here the text get method expects two indexesto fetch text names by tagadd first and last to the tag' name to get its start and end indexes to tag substringcall the text widget' tag_add method with tag name string and start and stop positions (text can also be tagged as added in insert callsto remove tag from all characters in range of textcall tag_remove tkinter tourpart
5,103
self text tag_add(selindex index self text tag_remove(sel' 'endtag all text in the widget select from index up to index remove selection from all text the first line here creates new tag that names all text in the widget--from start through end positions the second line adds range of characters to the built-in sel selection tag--they are automatically highlightedbecause this tag is predefined to configure its members that way the third line removes all characters in the text string from the sel tag (all selections are unselectednote that the tag_remove call just untags text within the named rangeto really delete tag completelycall tag_delete instead also keep in mind that these calls apply to tags themselvesto delete actual text use the delete method shown earlier you can map indexes to tags dynamicallytoo for examplethe text search method returns the row column index of the first occurrence of string between start and stop positions to automatically select the text thus foundsimply add its index to the builtin sel tagwhere self text search(targetinsertendpastit where ('+%dclen(target)self text tag_add(selwherepastitself text focus(search from insert cursor index beyond string found tag and select found string select text widget itself if you want only one string to be selectedbe sure to first run the tag_remove call listed earlier--this code adds selection in addition to any selections that already exist (it may generate multiple selections in the displayin generalyou can add any number of substrings to tag to process them as group to summarizeindexesmarksand tag locations can be used anytime you need text position for instancethe text see method scrolls the display to make position visibleit accepts all three kinds of position specifiersself text see(' 'self text see(insertself text see(sel_firstscroll display to top scroll display to insert cursor mark scroll display to selection tag text tags can also be used in broader ways for formatting and event bindingsbut 'll defer those details until the end of this section adding text-editing operations example - puts some of these concepts to work it extends example - to add support for four common text-editing operations--file savetext cut and pasteand string find searching--by subclassing scrolledtext to provide additional buttons and methods the text widget comes with set of default keyboard bindings that perform some common editing operationstoobut they might not be what is expected on every platformit' more common and user friendly to provide gui interfaces to editing operations in gui text editor text
5,104
""add common edit tools to scrolledtext by inheritancecomposition (embeddingwould work just as well herethis is not robust!--see pyedit for feature superset""from tkinter import from tkinter simpledialog import askstring from tkinter filedialog import asksaveasfilename from quitter import quitter from scrolledtext import scrolledtext herenot python' class simpleeditor(scrolledtext)see pyedit for more def __init__(selfparent=nonefile=none)frm frame(parentfrm pack(fill=xbutton(frmtext='save'command=self onsavepack(side=leftbutton(frmtext='cut'command=self oncutpack(side=leftbutton(frmtext='paste'command=self onpastepack(side=leftbutton(frmtext='find'command=self onfindpack(side=leftquitter(frmpack(side=leftscrolledtext __init__(selfparentfile=fileself text config(font=('courier' 'normal')def onsave(self)filename asksaveasfilename(if filenamealltext self gettext(open(filename' 'write(alltextdef oncut(self)text self text get(sel_firstsel_lastself text delete(sel_firstsel_lastself clipboard_clear(self clipboard_append(textfirst through last store text in file error if no select should wrap in try def onpaste(self)add clipboard text trytext self selection_get(selection='clipboard'self text insert(inserttextexcept tclerrorpass not to be pasted def onfind(self)target askstring('simpleeditor''search string?'if targetwhere self text search(targetinsertendfrom insert cursor if wherereturns an index print(wherepastit where ('+%dclen(target)index past target #self text tag_remove(sel' 'endremove selection self text tag_add(selwherepastitselect found target self text mark_set(insertpastitset insert mark self text see(insertscroll display tkinter tourpart
5,105
if __name__ ='__main__'if len(sys argv simpleeditor(file=sys argv[ ]mainloop(elsesimpleeditor(mainloop(select text widget filename on command line or notstart empty thistoowas written with one eye toward reuse--the simpleeditor class it defines could be attached or subclassed by other gui code as 'll explain at the end of this sectionthoughit' not yet as robust as general-purpose library tool should be stillit implements functional text editor in small amount of portable code when run standaloneit brings up the window in figure - (shown editing itself and running on windows)index positions are printed on stdout after each successful find operation--herefor two "deffindswith prior selection removal logic commentedout in the script (uncomment this line in the script to get single-selection behavior for finds) :\pp \gui\tourpython simpleedit py simpleedit py pp scrolledtext figure - simpleedit in action the save operation pops up the common save dialog that is available in tkinter and is tailored to look native on each platform figure - shows this dialog in action on windows find operations also pop up standard dialog box to input search string text
5,106
the find again (we willin ' more full-featured pyedit examplequit operations reuse the verifying quit button component we coded in yet againcode reuse means never having to say you're quitting without warning figure - save pop-up dialog on windows figure - find pop-up dialog using the clipboard besides text widget operationsexample - applies the tkinter clipboard interfaces in its cut-and-paste functions togetherthese operations allow you to move text within file (cut in one placepaste in anotherthe clipboard they use is just place to store data temporarily--deleted text is placed on the clipboard on cutand text is inserted from the clipboard on paste if we restrict our focus to this program alonethere really tkinter tourpart
5,107
variable but the clipboard is actually much larger concept the clipboard used by this script is an interface to system-wide storage spaceshared by all programs on your computer because of thatit can be used to transfer data between applicationseven ones that know nothing of tkinter for instancetext cut or copied in microsoft word session can be pasted in simpleeditor windowand text cut in simpleeditor can be pasted in microsoft notepad window (try itby using the clipboard for cut and pastesimpleeditor automatically integrates with the window system at large moreoverthe clipboard is not just for the text widget--it can also be used to cut and paste graphical objects in the canvas widget (discussed nextas used in the script of example - the basic tkinter clipboard interface looks like thisself clipboard_clear(self clipboard_append(texttext self selection_get(selection='clipboard'clear the clipboard store text string on it fetch contentsif any all of these calls are available as methods inherited by all tkinter widget objects because they are global in nature the clipboard selection used by this script is available on all platforms ( primary selection is also availablebut it is only generally useful on windowsso we'll ignore it herenotice that the clipboard selection_get call throws tclerror exception if it failsthis script simply ignores it and abandons paste requestbut we'll do better later composition versus inheritance as codedsimpleeditor uses inheritance to extend scrolledtext with extra buttons and callback methods as we've seenit' also reasonable to attach (embedgui objects coded as componentssuch as scrolledtext the attachment model is usually called compositionsome people find it simpler to understand and less prone to name clashes than extension by inheritance to give you an idea of the differences between these two approachesthe following sketches the sort of code you would write to attach scrolledtext to simpleeditor with changed lines in bold font (see the file simpleedit py in the book' examples distribution for complete composition implementationit' mostly matter of passing in the right parents and adding an extra st attribute name anytime you need to get to the text widget' methodsclass simpleeditor(frame)def __init__(selfparent=nonefile=none)frame __init__(selfparentself pack(frm frame(selffrm pack(fill=xbutton(frmtext='save'command=self onsavepack(side=leftmore text
5,108
self st scrolledtext(selffile=fileattachnot subclass self st text config(font=('courier' 'normal')def onsave(self)filename asksaveasfilename(if filenamealltext self st gettext(open(filename' 'write(alltextgo through attribute def oncut(self)text self st text get(sel_firstsel_lastself st text delete(sel_firstsel_lastmore this code doesn' need to subclass frame necessarily (it could add widgets to the passedin parent directly)but being frame allows the full package here to be embedded and configured as well the window looks identical when such code is run 'll let you be the judge of whether composition or inheritance is better here if you code your python gui classes rightthey will work under either regime it' called "simplefor reasonpyedit (aheadfinallybefore you change your system registry to make simpleeditor your default text file vieweri should mention that although it shows the basicsit' something of stripped-down version (reallya prototypeof the pyedit example we'll meet in in factyou may wish to study that example now if you're looking for more complete tkinter text-processing code in general therewe'll also use more advanced text operationssuch as the undo/redo interfacecase-insensitive searchesexternal files searchand more because the text widget is so powerfulit' difficult to demonstrate more of its features without the volume of code that is already listed in the pyedit program should also point out that simpleeditor not only is limited in functionbut also is just plain careless--many boundary cases go unchecked and trigger uncaught exceptions that don' kill the guibut are not handled or reported well even errors that are caught are not reported to the user ( paste with nothing to be pastedbe sure to see the pyedit example for more robust and complete implementation of the operations introduced in simpleeditor unicode and the text widget told you earlier that text content in the text widget is always string technicallythoughthere are two string types in python xstr for unicode textand bytes for byte strings moreovertext can be represented in variety of unicode encodings when stored on files it turns out that both these factors can impact programs that wish to use text well in python tkinter tourpart
5,109
international character sets for both str and bytesbut we must pass decoded unicode str to support the broadest range of character types in this sectionwe decompose the text story in tkinter in general to show why string types in the text widget you may or may not have noticedbut all our examples so far have been representing content as str strings--either hardcoded in scriptsor fetched and saved using simple text-mode files which assume the platform default encoding technicallythoughthe text widget allows us to insert both str and bytesfrom tkinter import text text( insert(' ''spam' insert('end' 'eggs' pack( get(' ''end''spameggs\ninsert str insert bytes "spameggsappears in text widget now fetch content inserting text as bytes might be useful for viewing arbitrary kinds of unicode textespecially if the encoding name is unknown for exampletext fetched over the internet ( attached to an email or fetched by ftpcould be in any unicode encodingstoring it in binary-mode files and displaying it as bytes in text widget may at least seem to side-step the encoding in our scripts unfortunatelythoughthe text widget returns its content as str stringsregardless of whether it was inserted as str or bytes--we get back already-decoded unicode text strings either wayt text( insert(' ''textfileline \ ' insert('end''textfileline \ ' get(' ''end''textfileline \ntextfileline \ \nt text( insert(' ' 'bytesfileline \ \ ' insert('end' 'bytesfileline \ \ ' get(' ''end''bytesfileline \ \nbytesfileline \ \ \ncontent is str for str pack(is irrelevent to get(content is str for bytes tooand \ displays as space in factwe get back str for content even if we insert both str and byteswith single \ added at the end for good measureas the first example in this section showshere' more comprehensive illustrationt text( insert(' ''textfileline \ ' insert('end''textfileline \ 'content is str for both insert(' ' 'bytesfileline \ \ 'one \ added for either type insert('end' 'bytesfileline \ \ 'pack(displays as lines get(' ''end''bytesfileline \ \ntextfileline \ntextfileline \nbytesfileline \ \ \ntext
5,110
print( get(' ''end')bytesfileline textfileline textfileline bytesfileline this makes it easy to perform text processing on content after it is fetchedwe may conduct it in terms of strregardless of which type of string was inserted howeverthis also makes it difficult to treat text data generically from unicode perspectivewe cannot save the returned str content to binary mode file as isbecause binary mode files expect bytes we must either encode to bytes manually first or open the file in text mode and rely on it to encode the str in either case we must know the unicode encoding name to applyassume the platform default sufficesfall back on guesses and hope one worksor ask the user in other wordsalthough tkinter allows us to insert and view some text of unknown encoding as bytesthe fact that it' returned as str strings means we generally need to know how to encode it anyhow on savesto satisfy python file interfaces moreoverbecause bytes inserted into text widgets must also be decodable according to the limited unicode policies of the underlying tk librarywe're generally better off decoding text to str ourselves if we wish to support unicode broadly to truly understand why that' truewe need to take brief excursion through the land of unicode unicode text in strings the reason for all this extra complexityof courseis that in world with unicodewe cannot really think of "textanymore without also asking "which kind text in general can be encoded in wide variety of unicode encoding schemes in pythonthis is always factor for str and pertains to bytes when it contains encoded text python' str unicode strings are simply strings once they are createdbut you have to take encodings into consideration when transferring them to and from files and when passing them to libraries that impose constraints on text encodings we won' cover unicode encodings it in depth here (see learning python for background detailsas well as the brief look at implications for files in )but quick review is in order to illustrate how this relates to text widgets first of allkeep in mind that ascii text data normally just works in most contextsbecause it is subset of most unicode encoding schemes data outside the ascii -bit rangethoughmay be represented differently as bytes in different encoding schemes for instancethe following must decode latin- bytes string using the latin- encoding--using the platform default or an explicitly named encoding that doesn' match the bytes will failb ' \xc \xe cb ' \xc \xe tkinter tourpart these bytes are latin- format text
5,111
unicodedecodeerror'utf codec can' decode bytes in position - invalid dat decode(unicodedecodeerror'utf codec can' decode bytes in position - invalid dat decode('latin ' 'aabaconce you've decoded to unicode stringyou can "convertit to variety of different encoding schemes reallythis simply translates to alternative binary encoding formatsfrom which we can decode again latera unicode string has no unicode type per seonly encoded binary data doess encode('latin- ' ' \xc \xe cs encode('utf- ' ' \xc \ \xc \xa cs encode('utf- ' '\xff\xfea\ \xc \ \ \xe \ \ encode('ascii'unicodeencodeerror'asciicodec can' encode character '\xc in position notice the last test herethe string you encode to must be compatible with the scheme you chooseor you'll get an exceptionhereascii is too narrow to represent characters decoded from latin- bytes even though you can convert to different (compatiblerepresentationsbytesyou must generally know what the encoded format is in order to decode back to strings encode('utf- 'decode('utf- ''aabacs encode('latin- 'decode('latin- ''aabacs encode('latin- 'decode('utf- 'unicodedecodeerror'utf codec can' decode bytes in position - invalid dat encode('utf- 'decode('latin- 'unicodeencodeerror'charmapcodec can' encode character '\xc in position note the last test here again technicallyencoding unicode code points (charactersto utf- bytes and then decoding back again per the latin- format does not raise an errorbut trying to print the result doesit' scrambled garbage to maintain fidelityyou must generally know what format encoded bytes are ins 'aabacx encode('utf- 'decode('utf- ' 'aabacx encode('latin- 'decode('latin- 'ok if encoding matches data any compatible encoding works text
5,112
'aabacx encode('utf- 'decode('latin- 'decoding worksresult is garbage unicodeencodeerror'charmapcodec can' encode character '\xc in position len( )len( ( no longer the same string encode('utf- ' ' \xc \ \xc \xa cx encode('utf- ' ' \xc \ \xc \ \xc \ \xc \xa cno longer same code points encode('latin- ' ' \xc \xe cx encode('latin- ' ' \xc \ \xc \xa ccuriouslythe original string may still be there after mismatch like this--if we encode the scrambled bytes back to latin- again (as -bit charactersand then decode properlywe might restore the original (in some contexts this can constitute sort of second chance if data is decoded wrong initially) 'aabacs encode('utf- 'decode('latin- 'unicodeencodeerror'charmapcodec can' encode character '\xc in position encode('utf- 'decode('latin- 'encode('latin- ' ' \xc \ \xc \xa cs encode('utf- 'decode('latin- 'encode('latin- 'decode('utf- ''aabacs encode('utf- 'decode('latin- 'encode('latin- 'decode('utf- '= true on the other handwe can use different encoding name to decodeas long as it' compatible with the format of the dataasciiutf- and latin- for instanceall format ascii text the same way'spamencode('utf 'decode('latin ''spam'spamencode('latin 'decode('ascii''spamit' important to remember that string' decoded value doesn' depend on the encoding it came from--once decodeda string has no notion of encoding and is simply sequence of unicode characters ("code points"hencewe really only need to care about encodings at the point of transfer to and from filess 'aabacs encode('utf- 'decode('utf- '= encode('latin- 'decode('latin- 'true tkinter tourpart
5,113
nowthe same rules apply to text filesbecause unicode strings are stored in files as encoded bytes when writingwe can encode in any format that accommodates the string' characters when readingthoughwe generally must know what that encoding is or provide one that formats characters the same wayopen('ldata'' 'encoding='latin- 'write( open('udata'' 'encoding='utf- 'write( open('ldata'' 'encoding='latin- 'read('aabacopen('udata'' 'encoding='utf- 'read('aabacstore in latin- format store in utf- format ok if correct name given open('ldata'' 'read(elsemay not work 'aabacopen('udata'' 'read(unicodeencodeerror'charmapcodec can' encode characters in position - cha open('ldata'' 'encoding='utf- 'read(unicodedecodeerror'utf codec can' decode bytes in position - invalid dat open('udata'' 'encoding='latin- 'read(unicodeencodeerror'charmapcodec can' encode character '\xc in position by contrastbinary mode files don' attempt to decode into unicode stringthey happily read whatever is presentwhether the data was written to the file in text mode with automatically encoded str strings (as in the preceding interactionor in binary mode with manually encoded bytes stringsopen('ldata''rb'read( ' \xc \xe copen('udata''rb'read( ' \xc \ \xc \xa copen('sdata''wb'writes encode('utf- 'open('sdata''rb'read( '\xff\xfea\ \xc \ \ \xe \ \ return value unicode and the text widget the application of all this to tkinter text displays is straightforwardif we open in binary mode to read byteswe don' need to be concerned about encodings in our own code-tkinter interprets the data as expectedat least for these two encodingsfrom tkinter import text text( insert(' 'open('ldata''rb'read() pack( get(' ''end''aabac\nstring appears in gui ok text
5,114
insert(' 'open('udata''rb'read() pack( get(' ''end''aabac\nstring appears in gui ok it works the same if we pass str fetched in text modebut we then need to know the encoding type on the python side of the fence--reads will fail if the encoding type doesn' match the stored datat text( insert(' 'open('ldata'' 'encoding='latin- 'read() pack( get(' ''end''aabac\nt text( insert(' 'open('udata'' 'encoding='utf- 'read() pack( get(' ''end''aabac\neither waythoughthe fetched content is always unicode strso binary mode really only addresses loadswe still need to know an encoding to storewhether we write in text mode directly or write in binary mode after manual encodingc get(' ''end' 'aabac\ncontent is str open('cdata''wb'write(ctypeerrormust be bytes or buffernot str binary mode needs bytes open('cdata'' 'encoding='latin- 'write(copen('cdata''rb'read( ' \xc \xe \ \neach write returns open('cdata'' 'encoding='utf- 'write(copen('cdata''rb'read( ' \xc \ \xc \xa \ \ndifferent bytes on files open('cdata'' 'encoding='utf- 'write(copen('cdata''rb'read( '\xff\xfea\ \xc \ \ \xe \ \ \ \ \ \ open('cdata''wb'writec encode('latin- 'open('cdata''rb'read( ' \xc \xe \nmanual encoding first same but no \ on win open('cdata'' 'encoding='ascii'write(cstill must be compatible unicodeencodeerror'asciicodec can' encode character '\xc in position notice the last test herelike manual encodingfile writes can still fail if the data cannot be encoded in the target scheme because of thatprograms may need to recover from tkinter tourpart
5,115
may be the default platform encoding the problem with treating text as bytes the prior sectionsrules may seem complexbut they boil down to the followingunless strings always use the platform defaultwe need to know encoding types to read or write in text mode and to manually decode or encode for binary mode we can use almost any encoding to write new files as long as it can handle the string' charactersbut must provide one that is compatible with the existing data' binary format on reads we don' need to know the encoding mode to read text as bytes in binary mode for displaybut the str content returned by the text widget still requires us to encode to write on saves so why not always load text files in binary mode to display them in tkinter text widgetwhile binary mode input files seem to side-step encoding issues for displaypassing text to tkinter as bytes instead of str really just delegates the encoding issue to the tk librarywhich imposes constraints of its own more specificallyopening input files in binary mode to read bytes may seem to support viewing arbitrary types of textbut it has two potential downsidesit shifts the burden of deciding encoding type from our script to the tk gui library the library must still determine how to render those bytes and may not support all encodings possible it allows opening and viewing data that is not text in naturethereby defeating some of the purpose of the validity checks performed by text decoding the first point is probably the most crucial here in experiments 've run on windowstk seems to correctly handle raw bytes strings encoded in asciiutf- and latin- formatbut not utf- or others such as cp by contrastthese all render correctly if decoded in python to str before being passed on to tk in programs intended for the world at largethis wider support is crucial today if you're able to know or ask for encodingsyou're better off using str both for display and saves to some degreeregardless of whether you pass in str or bytestkinter guis are subject to the constraints imposed by the underlying tk library and the tcl language it uses internallyas well as any imposed by the techniques python' tkinter uses to interface with tk for exampletclthe internal implementation language of the tk librarystores strings internally in utf- formatand decrees that strings passed in to and returned from its api be in this format text
5,116
supports translation using the platform and locale encodings in the local operating system with latin- as fallback python' tkinter passes bytes strings to tcl directlybut copies python str unicode strings to and from tcl unicode string objects tk inherits all of tcl' unicode policiesbut adds additional font selection policies for display in other wordsguis that display text in tkinter are somewhat at the mercy of multiple layers of softwareabove and beyond the python language itself in generalthoughunicode is broadly supported by tk' text widget for python strbut not for python bytes as you can probably tellthoughthis story quickly becomes very low-level and detailedso we won' explore it further in this booksee the web and other resources for more on tkintertkand tcland the interfaces between them other binary mode considerations even in contexts where it' sufficientusing binary mode files to finesse encodings for display is more complicated than you might think we always need to be careful to write output in binary modetooso what we read is what we later write--if we read in binary modecontent end-lines will be \ \ on windowsand we don' want textmode files to expand this to \ \ \ moreoverthere' another difference in tkinter for str and bytes str read from text-mode file appears in the gui as you expectand end-lines are mapped on windows as usualc:\pp \gui\tourpython from tkinter import text(str from text-mode file insert(' 'open('jack txt'read()platform default encoding pack(appears in gui normally get(' ''end')[: ' all work and no play makes jack dull boy \ all work and no plaif you pass in bytes obtained from binary-mode filehoweverit' odd in the gui on windows--there' an extra space at the end of each linewhich reflects the \ that is not stripped by binary mode filesc:\pp \gui\tourpython from tkinter import text(bytes from binary-mode insert(' 'open('jack txt''rb'read()no decoding occurs pack(lines have space at endt get(' ''end')[: ' all work and no play makes jack dull boy \ \ all work and no plto use bytes to allow for arbitrary text but make the text appear as expected by userswe also have to strip the \ characters at line end manually this assumes that \ \ combination doesn' mean something special in the text' encoding schemethough data in which this sequence does not mean end-of-line will likely have other issues when tkinter tourpart
5,117
binary mode for undecoded bytesbut drop \rc:\pp \gui\tourpython from tkinter import use bytesstrip \ if any text(data open('jack txt''rb'read(data data replace( '\ \ ' '\ ' insert(' 'datat pack( get(' ''end')[: ' all work and no play makes jack dull boy \ all work and no plato save content laterwe can either add the \ characters back on windows onlymanually encode to bytesand save in binary modeor we can open in text mode to make the file object restore the \ if needed and encode for usand write the str content string directly the second of these is probably simpleras we don' need to care about platform differences either waythoughwe still face an encoding step--we can either rely on the platform default encoding or obtain an encoding name from user interfaces in the followingfor examplethe text-mode file converts end-lines and encodes to bytes internally using the platform default if we care about supporting arbitrary unicode types or run on platform whose default does not accommodate characters displayedwe would need to pass in an explicit encoding argument (the python slice operation here has the same effect as fetching through tk' "end- cposition specification)continuing prior listing content get(' ''end')[:- open('copyjack txt'' 'write(content ^ drop added \ at end use platform default text mode adds \ on win :\pp \gui\tourfc jack txt copyjack txt comparing files jack txt and copyjack txt fcno differences encountered supporting unicode in pyedit (aheadwe'll see use case of accommodating the text widget' unicode behavior in the larger pyedit example of reallysupporting unicode just means supporting arbitrary unicode encodings in text files on opens and savesonce in memorytext processing can always be performed in terms of strsince that' how tkinter returns content to support unicodepyedit will open both input and output files in text mode with explicit encodings whenever possibleand fall back on opening input files in binary mode only as last resort this avoids relying on the limited unicode support tk provides for display of raw byte strings to make this policy workpyedit will accept encoding names from wide variety of sources and allow the user to configure which to attempt encodings may be obtained from user dialog inputsconfiguration file settingsthe platform defaultthe prior text
5,118
may also be desirable to limit encoding attempts to just one such source in some contexts watch for this code in franklypyedit in this edition originally read and wrote files in text mode with platform default encodings didn' consider the implications of unicode on pyedit until the pymailgui example' internet world raised the specter of arbitrary text encodings if it seems that strings are lot more complicated than they used to beit' probably only because your scope has been too narrow advanced text and tag operations but enough about the idiosyncrasies of unicode text--let' get back to coding guis besides the position specification roles we've seen so farthe text widget' text tags can also be used to apply formatting and behavior to all characters in substring and all substrings added to tag in factthis is where much of the power of the text widget liestags have formatting attributes for setting colorfonttabsand line spacing and justificationto apply these to many parts of the text at onceassociate them with tag and apply formatting to the tag with the tag_config methodmuch like the general config widget we've been using tags can also have associated event bindingswhich let you implement things such as hyperlinks in text widgetclicking the text triggers its tag' event handler tag bindings are set with tag_bind methodmuch like the general widget bind method we've already met with tagsit' possible to display multiple configurations within the same text widgetfor instanceyou can apply one font to the text widget at large and other fonts to tagged text in additionthe text widget allows you to embed other widgets at an index (they are treated like single character)as well as images example - illustrates the basics of all these advanced tools at once and draws the interface captured in figure - this script applies formatting and event bindings to three tagged substringsdisplays text in two different font and color schemesand embeds an image and button double-clicking any of the tagged substrings (or the embedded buttonwith mouse triggers an event that prints "got tag eventmessage to stdout example - pp \gui\tour\texttags py "demo advanced tag and text interfacesfrom tkinter import root tk(def hello(event)print('got tag event'make and config text tkinter tourpart
5,119
text config(font=('courier' 'normal')text config(width= height= text pack(expand=yesfill=bothtext insert(end'this is\ \nthe meaning\ \nof life \ \ 'embed windows and photos btn button(texttext='spam'command=lambdahello( )btn pack(text window_create(endwindow=btntext insert(end'\ \ 'img photoimage(file=/gifs/pythonpowered gif'text image_create(endimage=imgset font for all insert six lines embed button embed photo apply tags to substrings text tag_add('demo'' '' 'tag 'istext tag_add('demo'' '' 'tag 'thetext tag_add('demo'' '' 'tag 'lifetext tag_config('demo'background='purple'change colors in tag text tag_config('demo'foreground='white'not called bg/fg here text tag_config('demo'font=('times' 'underline')change font in tag text tag_bind('demo'''hellobind events in tag root mainloop(figure - text tags in action such embedding and tag tools could ultimately be used to render web page in factpython' standard html parser html parser module can help automate web page gui text
5,120
optionsconsult other tk and tkinter references right nowart class is about to begin canvas when it comes to graphicsthe tkinter canvas widget is the most free-form device in the library it' place to draw shapesmove objects dynamicallyand place other kinds of widgets the canvas is based on structured graphic object modeleverything drawn on canvas can be processed as an object you can get down to the pixel-by-pixel level in canvasbut you can also deal in terms of larger objects such as shapesphotosand embedded widgets the net result makes the canvas powerful enough to support everything from simple paint programs to full-scale visualization and animation basic canvas operations canvases are ubiquitous in much nontrivial gui workand we'll see larger canvas examples show up later in this book under the names pydrawpyphotopyviewpyclockand pytree for nowlet' jump right into an example that illustrates the basics example - runs most of the major canvas drawing methods example - pp \gui\tour\canvas py "demo all basic canvas interfacesfrom tkinter import canvas canvas(width= height= bg='white'canvas pack(expand=yesfill=both , is top left corner increases downright canvas create_line( canvas create_line( for in range( )canvas create_line( ifromxfromytoxtoy draw shapes canvas create_oval( width= fill='blue'canvas create_arc( canvas create_rectangle( width= fill='red'canvas create_line( width= fill='green'photo=photoimage(file=/gifs/ora-lp gif'canvas create_image( image=photoanchor=nwembed photo widget label(canvastext='spam'fg='white'bg='black'widget pack(canvas create_window( window=widgetembed widget canvas create_text( text='ham'draw some text mainloop( tkinter tourpart
5,121
photo on canvas and size canvas for photo earlier on this tour (see "imageson page this script also draws shapestextand even an embedded label widget its window gets by on looks alonein momentwe'll learn how to add event callbacks that let users interact with drawn items figure - canvas hardcoded object sketches programming the canvas widget canvases are easy to usebut they rely on coordinate systemdefine unique drawing methodsand name objects by identifier or tag this section introduces these core canvas concepts coordinates all items drawn on canvas are distinct objectsbut they are not really widgets if you study the canvas script closelyyou'll notice that canvases are created and packed (or gridded or placedwithin their parent container just like any other widget in tkinter but the items drawn on canvas are not shapesimagesand so onare positioned and moved on the canvas by coordinatesidentifiersand tags of thesecoordinates are the most fundamental part of the canvas model canvases define an ( ,ycoordinate system for their drawing areax means the horizontal scaley means vertical by defaultcoordinates are measured in screen pixels (dots)the upper-left corner of the canvas has coordinates ( , )and and coordinates canvas
5,122
this is different from the constraints we've used to pack widgets thus farbut it allows very fine-grained control over graphical layoutsand it supports more free-form interface techniques such as animation object construction the canvas allows you to draw and display common shapes such as linesovalsrectanglesarcsand polygons in additionyou can embed textimagesand other kinds of tkinter widgets such as labels and buttons the canvas script demonstrates all the basic graphic object constructor callsto eachyou pass one or more sets of ( ,ycoordinates to give the new object' locationstart point and endpointor diagonally opposite corners of bounding box that encloses the shapeid canvas create_line(fromxfromytoxtoyid canvas create_oval(fromxfromytoxtoyid canvas create_arcfromxfromytoxtoyid canvas create_rectangle(fromxfromytoxtoyline startstop two opposite box corners two opposite oval corners two opposite corners other drawing calls specify just one ( ,ypairto give the location of the object' upperleft cornerid canvas create_image( image=photoanchor=nwid canvas create_window( window=widgetid canvas create_text( text='ham'embed photo embed widget draw some text the canvas also provides create_polygon method that accepts an arbitrary set of coordinate arguments defining the endpoints of connected linesit' useful for drawing more arbitrary kinds of shapes composed of straight lines in addition to coordinatesmost of these drawing calls let you specify common configuration optionssuch as outline widthfill coloroutline colorand so on individual object types have unique configuration options all their owntoofor instancelines may specify the shape of an optional arrowand textwidgetsand images may be anchored to point of the compass (this looks like the packer' anchorbut really it gives point on the object that is positioned at the [ ,ycoordinates given in the create callnw puts the upper-left corner at [ , ]perhaps the most important thing to notice herethoughis that tkinter does most of the "gruntwork for you--when drawing graphicsyou provide coordinatesand shapes are automatically plotted and rendered in the pixel world if you've ever done any lower-level graphics workyou'll appreciate the difference animation techniques are covered at the end of this tour as use case examplebecause you can embed other widgets in canvas' drawing areatheir coordinate system also makes them ideal for implementing guis that let users design other guis by dragging embedded widgets around on the canvas-- useful canvas application we would explore in this book if had few hundred pages to spare tkinter tourpart
5,123
although not used by the canvas scriptevery object you put on canvas has an identifierreturned by the create_ method that draws or embeds the object (what was coded as id in the last section' examplesthis identifier can later be passed to other methods that move the object to new coordinatesset its configuration optionsdelete it from the canvasraise or lower it among other overlapping objectsand so on for instancethe canvas move method accepts both an object identifier and and offsets (not coordinates)and it moves the named object by the offsets givencanvas move(objectidortagoffsetxoffsetymove object(sby offset if this happens to move the object off-screenit is simply clipped (not shownother common canvas operations process objectstoocanvas delete(objectidortagcanvas tkraise(objectidortagcanvas lower(objectidortagcanvas itemconfig(objectidortagfill='red'delete object(sfrom canvas raise object(sto front lower object(sbelow others fill object(swith red color notice the tkraise name--raise by itself is reserved word in python also note that the itemconfig method is used to configure objects drawn on canvas after they have been createduse config to set configuration options for the canvas itself probably the best thing to notice herethoughis that because tkinter is based on structured objectsyou can process graphic object all at oncethere is no need to erase and redraw each pixel manually to implement move or raise canvas object tags but canvases offer even more power than suggested so far in addition to object identifiersyou can also perform canvas operations on entire sets of objects at onceby associating them all with taga name that you make up and apply to objects on the display tagging objects in canvas is at least similar in spirit to tagging substrings in the text widget we studied in the prior section in general termscanvas operation methods accept either single object' identifier or tag name for exampleyou can move an entire set of drawn objects by associating all with the same tag and passing the tag name to the canvas move method in factthis is why move takes offsetsnot coordinates--when given tageach object associated with the tag is moved by the same ( ,yoffsetsabsolute coordinates would make all the tagged objects appear on top of each other instead to associate an object with tageither specify the tag name in the object drawing call' tag option or call the addtag_withtag(tagobjectidortagcanvas method (or its relativesfor instancecanvas create_oval( fill='red'tag='bubbles'canvas create_oval( fill='red'tag='bubbles'objectid canvas create_oval( fill='red'canvas
5,124
canvas move('bubbles'diffxdiffythis makes three ovals and moves them at the same time by associating them all with the same tag name many objects can have the same tagmany tags can refer to the same objectand each tag can be individually configured and processed as in textcanvas widgets have predefined tag names toothe tag all refers to all objects on the canvasand current refers to whatever object is under the mouse cursor besides asking for an object under the mouseyou can also search for objects with the find_ canvas methodscanvas find_closest( , )for instancereturns tuple whose first item is the identifier of the closest object to the supplied coordinates--handy after you've received coordinates in general mouse-click event callback we'll revisit the notion of canvas tags by example later in this (see the animation scripts near the end if you need more details right awayas usualcanvases support additional operations and options that we don' have space to cover in finite text like this ( the canvas postscript method lets you save the canvas in postscript filesee later examples in this booksuch as pydrawfor more detailsand consult other tk or tkinter references for an exhaustive list of canvas object options scrolling canvases one canvas-related operation is so commonthoughthat it does merit look here as demonstrated in example - scroll bars can be cross-linked with canvas using the same protocols we used to add them to listboxes and text earlierbut with few unique requirements example - pp \gui\tour\scrolledcanvas py " simple vertically-scrollable canvas component and demofrom tkinter import class scrolledcanvas(frame)def __init__(selfparent=nonecolor='brown')frame __init__(selfparentself pack(expand=yesfill=bothcanv canvas(selfbg=colorrelief=sunkencanv config(width= height= canv config(scrollregion=( )canv config(highlightthickness= make me expandable display area size canvas size corners no pixels to border sbar scrollbar(selfsbar config(command=canv yviewcanv config(yscrollcommand=sbar setsbar pack(side=rightfill=ycanv pack(side=leftexpand=yesfill=bothxlink sbar and canv move one moves other pack first=clip last canv clipped first self fillcontent(canvcanv bind(''self ondoubleclickset event handler tkinter tourpart
5,125
def fillcontent(selfcanv)override me below for in range( )canv create_text( +( * )text='spam'+str( )fill='beige'def ondoubleclick(selfevent)override me below print(event xevent yprint(self canvas canvasx(event )self canvas canvasy(event )if __name__ ='__main__'scrolledcanvas(mainloop(this script makes the window in figure - it is similar to prior scroll examplesbut scrolled canvases introduce two new kinks in the scrolling modelscrollable versus viewable sizes you can specify the size of the displayed view windowbut you must specify the size of the scrollable canvas at large the size of the view window is what is displayedand it can be changed by the user by resizing the size of the scrollable canvas will generally be larger--it includes the entire contentof which only part is displayed in the view window scrolling moves the view window over the scrollable size canvas viewable to absolute coordinate mapping in additionyou may need to map between event view area coordinates and overall canvas coordinates if the canvas is larger than its view area in scrolling scenariothe canvas will almost always be larger than the part displayedso mapping is often needed when canvases are scrolled in some applicationsthis mapping is not requiredbecause widgets embedded in the canvas respond to users directly ( buttons in the pyphoto example in if the user interacts with the canvas directlythough ( in drawing program)mapping from view coordinates to scrollable size coordinates may be necessary figure - scrolledcanvas live canvas
5,126
and height options to specify an overall canvas sizegive the ( ,ycoordinates of the upper-left and lower-right corners of the canvas in four-item tuple passed to the scrollregion option if no view area size is givena default size is used if no scrollregion is givenit defaults to the view area sizethis makes the scroll bar uselesssince the view is assumed to hold the entire canvas mapping coordinates is bit subtler if the scrollable view area associated with canvas is smaller than the canvas at largethe ( ,ycoordinates returned in event objects are view area coordinatesnot overall canvas coordinates you'll generally want to scale the event coordinates to canvas coordinatesby passing them to the canvasx and canvasy canvas methods before using them to process objects for exampleif you run the scrolled canvas script and watch the messages printed on mouse double-clicksyou'll notice that the event coordinates are always relative to the displayed view windownot to the overall canvasc:\pp \gui\tourpython scrolledcanvas py event , when scrolled to top of canvas canvas , -sameas long as no border pixels event , when scrolled to bottom of canvas canvas , - differs radically when scrolled to midpoint in the canvas herethe mapped canvas is always the same as the canvas because the display area and canvas are both set at pixels wide (it would be off by pixels due to automatic borders if not for the script' highlightthickness settingbut notice that the mapped is wildly different from the event if you click after vertical scroll without scalingthe event' incorrectly points to spot much higher in the canvas many of this book' canvas examples need no such scaling--( , always maps to the upper-left corner of the canvas display in which mouse click occurs--but just because canvases are not scrolled see the next section for canvas with both horizontal and vertical scrollsthe pytree program later in this book is similarbut it also uses dynamically changed scrollable region sizes when new trees are viewed as rule of thumbif your canvases scrollbe sure to scale event coordinates to true canvas coordinates in callback handlers that care about positions some handlers might not care whether events are bound to individual drawn objects or embedded widgets instead of the canvas at largebut we need to move on to the next two sections to see how tkinter tourpart
5,127
at the end of we looked at collection of scripts that display thumbnail image links for all photos in directory therewe noted that scrolling is major requirement for large photo collections now that we know about canvases and scrollbarswe can finally put them to work to implement this much-needed extensionand conclude the image viewer story we began in (wellalmostexample - is mutation of the last codewhich displays thumbnails in scrollable canvas see the prior for more details on its operationincluding the imagetk module imported from the required python imaging library (pilthirdparty extension (needed for thumbnails and jpeg imagesin factto fully understand example - you must also refer to example - since we're reusing that module' thumbnail creator and photo viewer tools herewe are just adding canvaspositioning the fixed-size thumbnail buttons at absolute coordinates in the canvasand computing the scrollable size using concepts outlined in the prior section both horizontal and vertical scrollbars allow us to move through the canvas of image buttons freelyregardless of how many there may be example - pp \gui\pil\viewer_thumbs_scrolled py ""image viewer extensionuses fixed-size thumbnail buttons for uniform layoutand adds scrolling for large image sets by displaying thumbs in canvas widget with scroll barsrequires pil to view image formats such as jpegand reuses thumbs maker and single photo viewer in viewer_thumbs pycaveat/to dothis could also scroll popped-up images that are too large for the screenand are cropped on windows as issee pyphoto later in for much more complete version""import sysmath from tkinter import from pil imagetk import photoimage from viewer_thumbs import makethumbsviewone def viewer(imgdirkind=toplevelnumcols=noneheight= width= )""use fixed-size buttonsscrollable canvassets scrollable (fullsizeand places thumbs at absolute , coordinates in canvascaveatassumes all thumbs are same size ""win kind(win title('simple viewerimgdirquit button(wintext='quit'command=win quitbg='beige'quit pack(side=bottomfill=xcanvas canvas(winborderwidth= vbar scrollbar(winhbar scrollbar(winorient='horizontal'vbar pack(side=rightfill=ypack canvas after bars canvas
5,128
canvas pack(side=topfill=bothexpand=yesso clipped first vbar config(command=canvas yviewhbar config(command=canvas xviewcanvas config(yscrollcommand=vbar setcanvas config(xscrollcommand=hbar setcanvas config(height=heightwidth=widthcall on scroll move call on canvas move init viewable area size changes if user resizes [(imgfileimgobj)thumbs makethumbs(imgdirnumthumbs len(thumbsif not numcolsnumcols int(math ceil(math sqrt(numthumbs))fixed or numrows int(math ceil(numthumbs numcols) true div linksize max(thumbs[ ][ sizefullsize ( (linksize numcols)(linksize numrowscanvas config(scrollregion=fullsize(widthheightupper left , lower right , scrollable area size rowpos savephotos [while thumbsthumbsrowthumbs thumbs[:numcols]thumbs[numcols:colpos for (imgfileimgobjin thumbsrowphoto photoimage(imgobjlink button(canvasimage=photohandler lambda savefile=imgfileviewone(imgdirsavefilelink config(command=handlerwidth=linksizeheight=linksizelink pack(side=leftexpand=yescanvas create_window(colposrowposanchor=nwwindow=linkwidth=linksizeheight=linksizecolpos +linksize savephotos append(photorowpos +linksize return winsavephotos if __name__ ='__main__'imgdir 'imagesif len(sys argv else sys argv[ mainsave viewer(imgdirkind=tkmain mainloop(to see this program in actionmake sure you've installed the pil extension described near the end of and launch the script from command linepassing the name of the image directory to be viewed as command-line argument\pp \gui\pilviewer_thumbs_scrolled py :\users\mark\temp\ msdcf as beforeclicking on thumbnail image opens the corresponding image at its full size in new pop-up window figure - shows the viewer at work on large directory copied from my digital camerathe initial run must create and cache thumbnailsbut later runs start quickly tkinter tourpart
5,129
or simply run the script as is from command lineby clicking its file iconor within idle--without command-line argumentsit displays the contents of the default sample images subdirectory in the book' source code treeas captured in figure - figure - displaying the default images directory canvas
5,130
despite its evolutionary twiststhe scrollable thumbnail viewer in example - still has one major limitation remainingimages that are larger than the physical screen are simply truncated on windows when popped up this becomes glaringly obvious when opening large photos copied from digital camera like those in figure - moreoverthere is no way to resize images once openedto open other directoriesand so on it' fairly simplistic demonstration of canvas programming in we'll learn how to do better when we meet the pyphoto example program pyphoto will scroll the full size of images as well in additionit has tools for variety of resizing effectsand it supports saving images to files and opening other image directories on the fly at its corethoughpyphoto will reuse the techniques of our simple browser hereas well as the thumbnail generation code we wrote in the prior much like our simple text editor earlier in the the code here is essentially prototype for the more complete pyphoto program we'll put together later in stay tuned for the thrilling conclusion of the pyphoto story (or flip ahead now if the suspense is too much to bearfor the purposes of this notice how in example - the thumbnail viewer' actions are associated with embedded button widgetsnot with the canvas itself in factthe canvas isn' much but display device to see how to enrich it with events of its ownlet' move on to the next section using canvas events like text and listboxthere is no notion of single command callback for canvas insteadcanvas programs generally use other widgets (as we did with example - ' thumbnail buttonsor the lower-level bind call to set up handlers for mouse clickskey pressesand the like (as we did for example - ' scrolling canvasexample - takes the latter approach furthershowing how to bind additional events for the canvas itselfin order to implement few of the more common canvas drawing operations example - pp \gui\tour\canvasdraw py ""draw elastic shapes on canvas on dragmove on right clicksee canvasdraw_tagspy for extensions with tags and animation ""from tkinter import trace false class canvaseventsdemodef __init__(selfparent=none)canvas canvas(width= height= bg='beige'canvas pack(canvas bind(''self onstartclick canvas bind(''self ongrowand drag tkinter tourpart
5,131
self oncleardelete all canvas bind(''self onmovemove latest self canvas canvas self drawn none self kinds [canvas create_ovalcanvas create_rectangledef onstart(selfevent)self shape self kinds[ self kinds self kinds[ :self kinds[: self start event self drawn none start dragout def ongrow(selfevent)delete and redraw canvas event widget if self drawncanvas delete(self drawnobjectid self shape(self start xself start yevent xevent yif traceprint(objectidself drawn objectid def onclear(selfevent)event widget delete('all'use tag all def onmove(selfevent)if self drawnmove to click spot if traceprint(self drawncanvas event widget diffxdiffy (event self start )(event self start ycanvas move(self drawndiffxdiffyself start event if __name__ ='__main__'canvaseventsdemo(mainloop(this script intercepts and processes three mouse-controlled actionsclearing the canvas to erase everything on the canvasthe script binds the double left-click event to run the canvas' delete method with the all tag--againa built-in tag that associates every object on the screen notice that the canvas widget clicked is available in the event object passed in to the callback handler (it' also available as self canvasdragging out object shapes pressing the left mouse button and dragging (moving it while the button is still pressedcreates rectangle or oval shape as you drag this is often called dragging out an object--the shape grows and shrinks in an elastic rubber-band fashion as you drag the mouse and winds up with final size and location given by the point where you release the mouse button to make this work in tkinterall you need to do is delete the old shape and draw another as each drag event firesboth delete and draw operations are fast enough to achieve the elastic drag-out effect of courseto draw shape to the current canvas
5,132
remember the last drawn object' identifier two events come into playthe initial button press event saves the start coordinates (reallythe initial press event objectwhich contains the start coordinates)and mouse movement events erase and redraw from the start coordinates to the new mouse coordinates and save the new object id for the next event' erase object moves when you click the right mouse button (button )the script moves the most recently drawn object to the spot you clicked in single step the event argument gives the ( ,ycoordinates of the spot clickedand we subtract the saved starting coordinates of the last drawn object to get the ( ,yoffsets to pass to the canvas move method (againmove does not take positionsremember to scale event coordinates first if your canvas is scrolled the net result creates window like that shown in figure - after user interaction as you drag out objectsthe script alternates between ovals and rectanglesset the script' trace global to watch object identifiers scroll on stdout as new objects are drawn during drag this screenshot was taken after few object drag-outs and movesbut you' never tell from looking at itrun this example on your own computer to get better feel for the operations it supports figure - canvasdraw after few drags and moves tkinter tourpart
5,133
much like we did for the text widgetit is also possible to bind events for one or more specific objects drawn on canvas with its tag_bind method this call accepts either tag name string or an object id in its first argument for instanceyou can register different callback handler for mouse clicks on every drawn item or on any in group of drawn and tagged itemsrather than for the entire canvas at large example - binds double-click handler on both the canvas itself and on two specific text items within itto illustrate the interfaces it generates figure - when run example - pp \gui\tour\canvas-bind py bind events on both canvas and its items from tkinter import def oncanvasclick(event)print('got canvas click'event xevent yevent widgetdef onobjectclick(event)print('got object click'event xevent yevent widgetend='print(event widget find_closest(event xevent )find text object' id root tk(canv canvas(rootwidth= height= obj canv create_text( text='click me one'obj canv create_text( text='click me two'canv bind(''oncanvasclickcanv tag_bind(obj ''onobjectclickcanv tag_bind(obj ''onobjectclickcanv pack(root mainloop(bind to whole canvas bind to drawn item tag works here too figure - canvas-bind window object ids are passed to tag_bind herebut tag name string would work tooand would allow you to associate multiple canvas objects as group for event purposes when you click outside the text items in this script' windowthe canvas event handler fireswhen either text item is clickedboth the canvas and the text object handlers fire here is the stdout result after clicking on the canvas twice and on each text item oncecanvas
5,134
text item clicked (the one closest to the click spot) :\pp \gui\tourpython canvas-bind py got canvas click canvas clicks got canvas click got object click ( ,first text click got canvas click got object click ( ,second text click got canvas click we'll revisit the notion of events bound to canvases in the pydraw example in where we'll use them to implement feature-rich paint and motion program we'll also return to the canvasdraw script later in this to add tag-based moves and simple animation with time-based toolsso keep this page bookmarked for reference firstthoughlet' follow promising side road to explore another way to lay out widgets within windows--the gridding layout model grids so farwe've mostly been arranging widgets in displays by calling their pack methods-an interface to the packer geometry manager in tkinter we've also used absolute coordinates in canvaseswhich are kind of layout schemetoobut not high-level managed one like the packer this section introduces gridthe most commonly used alternative to the packer we previewed this alternative in when discussing input forms and arranging image thumbnails herewe'll study gridding in its full form as we learned earliertkinter geometry managers work by arranging child widgets within parent container widget (parents are typically frames or top-level windowswhen we ask widget to pack or grid itselfwe're really asking its parent to place it among its siblings with packwe provide constraints or sides and let the geometry manager lay out widgets appropriately with gridwe arrange widgets in rows and columns in their parentas though the parent container widget was table gridding is an entirely distinct geometry management system in tkinter in factat this writingpack and grid are mutually exclusive for widgets that have the same parent-within given parent containerwe can either pack widgets or grid thembut we cannot do both that makes senseif you realize that geometry managers do their jobs as parentsand widget can be arranged by only one geometry manager why gridsat least within one containerthoughthat means you must pick either grid or pack and stick with it so why gridthenin generalgrid is handy for displays in which otherwise unrelated widgets must line up horizontally this includes both tabular displays and form-like displaysarranging input fields in row/column grid fashion can be at least as easy as laying out the display with nested frames tkinter tourpart
5,135
as grids or as row frames with fixed-width labelsso that labels and entry fields line up horizontally as expected on all platforms (as we learnedcolumn frames don' work reliablybecause they may misalign rowsalthough grids and row frames are roughly the same amount of workgrids are useful if calculating maximum label width is inconvenient moreovergrids also apply to tables more complex than forms as we'll seethoughfor input formsgrid doesn' offer substantial code or complexity savings compared to equivalent packer solutionsespecially when things like resizability are added to the gui picture in other wordsthe choice between the two layout schemes is often largely one of stylenot technology grid basicsinput forms revisited let' start off with the basicsexample - lays out table of labels and entry fields-widgets we've already met herethoughthey are arrayed on grid example - pp \gui\tour\grid\grid py from tkinter import colors ['red''green''orange''white''yellow''blue' for in colorslabel(text=crelief=ridgewidth= grid(row=rcolumn= entry(bg=crelief=sunkenwidth= grid(row=rcolumn= + mainloop(gridding assigns widgets to row and column numberswhich both begin at number tkinter uses these coordinatesalong with widget size in generalto lay out the container' display automatically this is similar to the packerexcept that rows and columns replace the packer' notion of sides and packing order when runthis script creates the window shown in figure - pictured with data typed into few of the input fields once againthis book won' do justice to the colors displayed on the rightso you'll have to stretch your imagination little (or run this script on computer of your owndespite its colorsthis is really just classic input form layout againof the same kind we met in the prior labels on the left describe data to type into entry fields on the right herethoughwe achieve the layout with gridding instead of packed frames just for funthis script displays color names on the left and the entry field of the corresponding color on the right it achieves its table-like layout with these lineslabelgrid(row=rcolumn= entrygrid(row=rcolumn= grids
5,136
from the perspective of the container windowthe label is gridded to column in the current row number ( counter that starts at and the entry is placed in column the upshot is that the grid system lays out all the labels and entries in two-dimensional table automaticallywith both evenly sized rows and evenly sized columns large enough to hold the largest item in each column that isbecause widgets are arranged by both row and column when griddedthey align properly in both dimensions although packed row frames can achieve the same effect if labels are fixed width (as we learned in )grids directly reflect the structure of tabular displaysthis includes input formsas well as larger tables in general the next section illustrates this difference in code comparing grid and pack time for some compare-and-contrastexample - implements the same sort of colorized input form with both grid and packto make it easy to see the differences between the two approaches example - pp \gui\tour\grid\grid py ""add equivalent pack window using row frames and fixed-width labelslabels and entrys in packed column frames may not line up horizontallysame length codethough enumerate built-in could trim lines off grid""from tkinter import colors ['red''green''orange''white''yellow''blue'def gridbox(parent)"grid by row/column numbersrow for color in colorslab label(parenttext=colorrelief=ridgewidth= ent entry(parentbg=colorrelief=sunkenwidth= lab grid(row=rowcolumn= ent grid(row=rowcolumn= tkinter tourpart
5,137
row + def packbox(parent)"row frames with fixed-width labelsfor color in colorsrow frame(parentlab label(rowtext=colorrelief=ridgewidth= ent entry(rowbg=colorrelief=sunkenwidth= row pack(side=toplab pack(side=leftent pack(side=rightent insert( 'pack'if __name__ ='__main__'root tk(gridbox(toplevel()packbox(toplevel()button(roottext='quit'command=root quitpack(mainloop(the pack version here uses row frames with fixed-width labels (againcolumn frames can skew rowsthe basic label and entry widgets are created the same way by these two functionsbut they are arranged in very different wayswith packwe use side options to attach labels and rows on the left and rightand create frame for each row (itself attached to the parent' current topwith gridwe instead assign each widget row and column position in the implied tabular grid of the parentusing options of the same name as we've learnedwith packthe packing order can mattertooa widget gets an entire side of the remaining space (mostly irrelevant here)and items packed first are clipped last (labels and topmost rows disappear last herethe grid alternative achieves the same clipping effect by virtue of grid behavior running the script makes the windows in figure - --one window for each scheme if you study this example closelyyou'll find that the difference in the amount of code required for each layout scheme is roughly washat least in this simple form the pack scheme must create frame per rowbut the grid scheme must keep track of the current row number in factboth schemes require the same number of code lines as shownthough to be fair we could shave one line from each by packing or gridding the label immediatelyand could shave two more lines from the grid layout by using the built-in enumerate function to avoid manual counting here' minimalist' version of the grid box function for referencedef gridbox(parent)for (rowcolorin enumerate(colors)label(parenttext=colorrelief=ridgewidth= grid(row=rowcolumn= ent entry(parentbg=colorrelief=sunkenwidth= grids
5,138
ent grid(row=rowcolumn= ent insert( 'grid'we'll leave further code compaction to the more serious sports fans in the audience (this code isn' too horrificbut making your code concise in general is not always in your coworkersbest interest!irrespective of coding tricksthe complexity of packing and gridding here seems similar as we'll see laterthoughgridding can require more code when widget resizing is factored into the mix combining grid and pack notice that the prior section' example - passes brand-new toplevel to each form constructor function so that the grid and pack versions wind up in distinct top-level windows because the two geometry managers are mutually exclusive within given parent containerwe have to be careful not to mix them improperly for instanceexample - is able to put both the packed and the gridded widgets on the same windowbut only by isolating each in its own frame container widget example - pp \gui\tour\grid\grid -same py ""build pack and grid forms on different frames in same windowcan' grid and pack in same parent container ( root windowbut can mix in same window if done in different parent frames""from tkinter import from grid import gridboxpackbox root tk(label(roottext='grid:'pack( tkinter tourpart
5,139
frm pack(padx= pady= gridbox(frmlabel(roottext='pack:'pack(frm frame(rootbd= relief=raisedfrm pack(padx= pady= packbox(frmbutton(roottext='quit'command=root quitpack(mainloop(when this runs we get composite window with two forms that look identical (figure - )but the two nested frames are actually controlled by completely different geometry managers figure - grid and pack in the same window on the other handthe sort of code in example - fails badlybecause it attempts to use pack and grid within the same parent--only one geometry manager can be used on any one parent example - pp \gui\tour\grid\grid -fails py ""fails-can' grid and pack in same parent container (hereroot window""grids
5,140
from grid import gridboxpackbox root tk(gridbox(rootpackbox(rootbutton(roottext='quit'command=root quitpack(mainloop(this script passes the same parent (the top-level windowto each function in an effort to make both forms appear in one window it also utterly hangs the python process on my machinewithout ever showing any windows at all (on some versions of windowsi've had to resort to ctrl-alt-delete to kill iton othersthe command prompt shell window must sometimes be restarted altogethergeometry manager combinations can be subtle until you get the hang of this to make this example workfor instancewe simply need to isolate the grid box in parent container all its own to keep it away from the packing going on in the root window-as in the following bold alternative coderoot tk(frm frame(rootfrm pack(this works gridbox(frmgridbox must have its own parent in which to grid packbox(rootbutton(roottext='quit'command=root quitpack(mainloop(againtoday you must either pack or grid within one parentbut not both it' possible that this restriction may be lifted in the futurebut it' been long-lived constraintand it seems unlikely to be removedgiven the disparity in the two window manager schemestry your python to be sure making gridded widgets expandable and nowsome practical bitsthe grids we've seen so far are fixed in sizethey do not grow when the enclosing window is resized by user example - implements an unreasonably patriotic input form with both grid and pack againbut adds the configuration steps needed to make all widgets in both windows expand along with their window on resize example - pp \gui\tour\grid\grid py "add label on the top and form resizingfrom tkinter import colors ['red''white''blue'def gridbox(root)label(roottext='grid'grid(columnspan= tkinter tourpart
5,141
for color in colorslab label(roottext=colorrelief=ridgewidth= ent entry(rootbg=colorrelief=sunkenwidth= lab grid(row=rowcolumn= sticky=nsewent grid(row=rowcolumn= sticky=nsewroot rowconfigure(rowweight= row + root columnconfigure( weight= root columnconfigure( weight= def packbox(root)label(roottext='pack'pack(for color in colorsrow frame(rootlab label(rowtext=colorrelief=ridgewidth= ent entry(rowbg=colorrelief=sunkenwidth= row pack(side=topexpand=yesfill=bothlab pack(side=leftexpand=yesfill=bothent pack(side=rightexpand=yesfill=bothroot tk(gridbox(toplevel(root)packbox(toplevel(root)button(roottext='quit'command=root quitpack(mainloop(when runthis script makes the scene in figure - it builds distinct pack and grid windows againwith entry fields on the right colored redwhiteand blue (or for readers not working along on computergraywhiteand marginally darker grayfigure - grid and pack windows before resizing this timethoughresizing both windows with mouse drags makes all their embedded labels and entry fields expand along with the parent windowas we see in figure - (with text typed into the formgrids
5,142
as codedshrinking the pack window clips items packed lastshrinking the grid window shrinks all labels and entries together unlike grid ' default behavior (try this on your ownresizing in grids now that 've shown you what these windows doi need to explain how they do it we learned in how to make widgets expand with packwe use expand and fill options to increase space allocations and stretch into themrespectively to make expansion work for widgets arranged by gridwe need to use different protocols rows and columns must be marked with weight to make them expandableand widgets must also be made sticky so that they are stretched within their allocated grid cellheavy rows and columns with packwe make each row expandable by making the corresponding frame expandablewith expand=yes and fill=both gridders must be bit more specificto get full expandabilitycall the grid container' rowconfigure method for each row and its columnconfigure for each column to both methodspass weight option with value greater than zero to enable rows and columns to expand weight defaults to zero (which means no expansion)and the grid container in this script is just the top-level window using different weights for different rows and columns makes them grow at proportionally different rates sticky widgets with packwe use fill options to stretch widgets to fill their allocated space horizontally or verticallyand anchor options to position widgets within their allocated tkinter tourpart
5,143
packer gridded widgets can optionally be made sticky on one side of their allocated cell space (such as anchoror on more than one side to make them stretch (such as fillwidgets can be made sticky in four directions--nseand wand concatenations of these letters specify multiple-side stickiness for instancea sticky setting of left justifies the widget in its allocated space (such as packer anchor= )and ns stretches the widget vertically within its allocated space (such as packer fill=ywidget stickiness hasn' been useful in examples thus far because the layouts were regularly sized (widgets were no smaller than their allocated grid cell space)and resizes weren' supported at all herethoughexample - specifies nsew stickiness to make widgets stretch in all directions with their allocated cells different combinations of row and column weights and sticky settings generate different resize effects for instancedeleting the columnconfig lines in the grid script makes the display expand vertically but not horizontally try changing some of these settings yourself to see the sorts of effects they produce spanning columns and rows there is one other big difference in how the grid script configures its windows both the grid and the pack windows display label on the top that spans the entire window for the packer schemewe simply make label attached to the top of the window at large (rememberside defaults to top)label(roottext='pack'pack(because this label is attached to the window' top before any row frames areit appears across the entire window top as expected but laying out such label takes bit more work in the rigid world of gridsthe first line of the grid implementation function does it like thislabel(roottext='grid'grid(columnspan= to make widget span across multiple columnswe pass grid columnspan option with spanned-column count hereit just specifies that the label at the top of the window should stretch over the entire window--across both the label and the entry columns to make widget span across multiple rowspass rowspan option instead the regular layouts of grids can be either an asset or liabilitydepending on how regular your user interface will bethese two span settings let you specify exceptions to the rule when needed so which geometry manager comes out on top herewhen resizing is factored inas in the script in example - gridding actually becomes slightly more complexin factgridding requires three extra lines of code on the other handenumerate could again make the race closegrid is still convenient for simple formsand your grids and packs may vary grids
5,144
we'll code near the end of and use again in when developing file transfer and ftp client user interface as we'll seedoing forms well once allows us to skip the details later we'll also use more custom form layout code in the pyedit program' change dialog in and the pymailgui example' email header fields in laying out larger tables with grid so farwe've been building two-column arrays of labels and input fields that' typical of input formsbut the tkinter grid manager is capable of configuring much grander matrixes for instanceexample - builds five-row by four-column array of labelswhere each label simply displays its row and column number (row colwhen runthe window in figure - appears on-screen example - pp \gui\tour\grid\grid py simple tablein default tk root window from tkinter import for in range( )for in range( )lab label(text='% % (ij)relief=ridgelab grid(row=icolumn=jsticky=nsewmainloop(figure - array of coordinate labels if you think this is starting to look like it might be way to program spreadsheetsyou may be on to something example - takes this idea bit further and adds button that prints the table' current input field values to the stdout stream (usuallyto the console window tkinter tourpart
5,145
table of input fieldsdefault tk root window from tkinter import rows [for in range( )cols [for in range( )ent entry(relief=ridgeent grid(row=icolumn=jsticky=nsewent insert(end'% % (ij)cols append(entrows append(colsdef onpress()for row in rowsfor col in rowprint(col get()end='print(button(text='fetch'command=onpressgrid(mainloop(when runthis script creates the window in figure - and saves away all the grid' entry field widgets in two-dimensional list of lists when its fetch button is pressedthe script steps through the saved list of lists of entry widgetsto fetch and display all the current values in the grid here is the output of two fetch presses--one before made input field changesand one afterc:\pp \gui\tour\gridpython grid py now that we know how to build and step through arrays of input fieldslet' add few more useful buttons example - adds another row to display column sums and adds buttons to clear all fields to zero and calculate column sums example - pp \gui\tour\grid\grid py add column sumsclearing from tkinter import numrownumcol grids
5,146
rows [for in range(numrow)cols [for in range(numcol)ent entry(relief=ridgeent grid(row=icolumn=jsticky=nsewent insert(end'% % (ij)cols append(entrows append(colssums [for in range(numcol)lab label(text='?'relief=sunkenlab grid(row=numrowcolumn=isticky=nsewsums append(labdef onprint()for row in rowsfor col in rowprint(col get()end='print(print(def onsum()tots [ numcol for in range(numcol)for in range(numrow)tots[ +eval(rows[ ][iget()for in range(numcol)sums[iconfig(text=str(tots[ ])sum column display in gui def onclear()for row in rowsfor col in rowcol delete(' 'endcol insert(end' 'for sum in sumssum config(text='?'import sys button(text='sum'command=onsumgrid(row=numrow+ column= button(text='print'command=onprintgrid(row=numrow+ column= tkinter tourpart
5,147
button(text='quit'command=sys exitgrid(row=numrow+ column= mainloop(figure - shows this script at work summing up four columns of numbersto get different-size tablechange the numrow and numcol variables at the top of the script figure - adding column sums and finallyexample - is one last extension that is coded as class for reusabilityand it adds button to load the table' data from file data files are assumed to be coded as one line per rowwith whitespace (spaces or tabsbetween each column within row line loading file of data automatically resizes the table gui to accommodate the number of columns in the table based upon the file' content example - pp \gui\tour\grid\grid py recode as an embeddable class from tkinter import from tkinter filedialog import askopenfilename from pp gui tour quitter import quitter reusepackand grid class sumgrid(frame)def __init__(selfparent=nonenumrow= numcol= )frame __init__(selfparentself numrow numrow am frame container self numcol numcol caller packs or grids me self makewidgets(numrownumcolelse only usable one way def makewidgets(selfnumrownumcol)self rows [for in range(numrow)cols [for in range(numcol)ent entry(selfrelief=ridgeent grid(row= + column=jsticky=nsewent insert(end'% % (ij)cols append(entself rows append(colsgrids
5,148
for in range(numcol)lab label(selftext='?'relief=sunkenlab grid(row=numrow+ column=isticky=nsewself sums append(labbutton(selftext='sum'command=self onsumgrid(row= column= button(selftext='print'command=self onprintgrid(row= column= button(selftext='clear'command=self oncleargrid(row= column= button(selftext='load'command=self onloadgrid(row= column= quitter(selfgrid(row= column= failsquitter(selfpack(def onprint(self)for row in self rowsfor col in rowprint(col get()end='print(print(def onsum(self)tots [ self numcol for in range(self numcol)for in range(self numrow)tots[ +eval(self rows[ ][iget()for in range(self numcol)self sums[iconfig(text=str(tots[ ])def onclear(self)for row in self rowsfor col in rowcol delete(' 'endcol insert(end' 'for sum in self sumssum config(text='?'def onload(self)file askopenfilename(if filefor row in self rowsfor col in rowcol grid_forget(for sum in self sumssum grid_forget(filelines open(file' 'readlines(self numrow len(filelinesself numcol len(filelines[ split()self makewidgets(self numrowself numcolsum current data delete content preserve display erase current gui load file data resize to data for (rowlinein enumerate(filelines)load into gui fields line split(for col in range(self numcol)self rows[row][coldelete(' 'endself rows[row][colinsert(endfields[col] tkinter tourpart
5,149
import sys root tk(root title('summer grid'if len(sys argv! sumgrid(rootpack(grid(works here too elserowscols eval(sys argv[ ])eval(sys argv[ ]sumgrid(rootrowscolspack(mainloop(notice that this module' sumgrid class is careful not to either grid or pack itself in order to be attachable to containers where other widgets are being gridded or packedit leaves its own geometry management ambiguous and requires callers to pack or grid its instances it' ok for containers to pick either scheme for their own children because they effectively seal off the pack-or-grid choice but attachable component classes that aim to be reused under both geometry managers cannot manage themselves because they cannot predict their parent' policy this is fairly long example that doesn' say much else about gridding or widgets in generalso 'll leave most of it as suggested reading and just show what it does figure - shows the initial window created by this script after changing the last column and requesting summake sure the directory containing the pp examples root is on your module search path ( pythonpathfor the package import by defaultthe class makes the grid herebut we can pass in other dimensions to both the class constructor and the script' command line when you press the load buttonyou get the standard file selection dialog we met earlier on this tour (figure - the datafile grid-data txt contains seven rows and six columns of datac:\pp \gui\tour\gridtype grid -data txt loading this file' data into our gui makes the dimensions of the grid change accordingly--the class simply reruns its widget construction logic after erasing all the old entry widgets with the grid_forget method the grid_forget method unmaps gridded widgets and so effectively erases them from the display also watch for the pack_forget widget and window withdraw methods used in the after event "alarmexamples of the next section for other ways to erase and redraw gui components once the gui is erased and redrawn for the new datafigure - captures the scene after the file load and new sum have been requested by the user in the gui grids
5,150
figure - opening data file for sumgrid figure - data file loadeddisplayedand summed tkinter tourpart
5,151
of its columnsnot just simple numbers because this script converts input field values with the python eval built-in functionany python syntax will work in this table' fieldsas long as it can be parsed and evaluated within the scope of the onsum methodc:\pp \gui\tour\gridtype grid -data txt * - << % pow( , ** [ , ][ {' ': }[' ' len('abcd' abs(- eval(' + ' summing these fields runs the python code they containas seen in figure - this can be powerful featureimagine full-blown spreadsheet gridfor instance--field values could be python code "snippetsthat compute values on the flycall functions in modulesand even download current stock quotes over the internet with tools we'll meet in the next part of this book figure - python expressions in the data and table it' also potentially dangerous tool-- field might just contain an expression that erases your hard drive!if you're not sure what expressions may doeither don' use eval (convert with more limited built-in functions like int and float insteador make sure your python is running in process with restricted access permissions for system components you don' want to expose to the code you run of coursethis still is nowhere near true spreadsheet program there are fixed column sums and file loadsfor instancebut individual cells cannot contain formulas based debated showing thisbut since understanding danger is big part of avoiding it--if the python process had permission to delete filespassing the code string __import__('os'system('rm -rf *'to eval on unix would delete all files at and below the current directory by running shell command (and 'rmdir / / would have similar effect on windowsdon' do thisto see how this works in less devious and potentially useful waytype __import__('math'pi into one of the gui table' cells--on sumthe cell evaluates to pi ( passing "__import__('os'system('dir')to eval interactively proves the point safely as well all of this also applies to the exec built-in--eval runs expression strings and exec statementsbut expressions are statements (though not vice versaa typical user of most guis is unlikely to type this kind of code accidentallyof courseespecially if that user is always youbut be careful out theregrids
5,152
exercises should also point out that there is more to gridding than we have time to present fully here for instanceby creating subframes that have grids of their ownwe can build up more sophisticated layouts as component hierarchies in much the same way as nested frames arranged with the packer for nowlet' move on to one last widget survey topic time toolsthreadsand animation the last stop on our widget tour is perhaps the most unique tkinter also comes with handful of tools that have to do with the event-driven programming modelnot graphics displayed on computer screen some gui applications need to perform background activities periodically for exampleto "blinka widget' appearancewe' like to register callback handler to be invoked at regular time intervals similarlyit' not good idea to let long-running file operation block other activity in guiif the event loop could be forced to update periodicallythe gui could remain responsive tkinter comes with tools for both scheduling such delayed actions and forcing screen updateswidget after(millisecondsfunction*argsthis tool schedules the function to be called once by the gui' event processing system after number of milliseconds this form of the call does not pause the program--the callback function is scheduled to be run later from the normal tkinter event loopbut the calling program continues normallyand the gui remains active while the function call is pending as also discussed in unlike the threading module' timer objectwidget after events are dispatched in the main gui thread and so can freely update the gui the function event handler argument can be any callable python objecta functionbound methodlambda and so on the milliseconds timer duration argument is an integer which can be used to specify both fractions and multiples of secondits value divided by , gives equivalent seconds any args arguments are passed by position to function when it is later called in practicea lambda can be used in place of individually-listed arguments to make the association of arguments to function explicitbut that is not required when the function is methodobject state information (attributesmight also provide its data instead of listed arguments the after method returns an id that can be passed to after_cancel to cancel the callback since this method is so commonly usedi'll say more about it by example in moment widget after(millisecondsthis tool pauses the calling program for number of milliseconds--for examplean argument of , pauses the caller for seconds this is essentially equivalent to python' library function time sleep(seconds)and both calls can be used to tkinter tourpart
5,153
and the simpler examples aheadwidget after_idle(function*argsthis tool schedules the function to be called once when there are no more pending events to process that isfunction becomes an idle handlerwhich is invoked when the gui isn' busy doing anything else widget after_cancel(idthis tool cancels pending after callback event before it occursid is the return value of an after event scheduling call widget update(this tool forces tkinter to process all pending events in the event queueincluding geometry resizing and widget updates and redraws you can call this periodically from long-running callback handler to refresh the screen and perform any updates to it that your handler has already requested if you don'tyour updates may not appear on-screen until your callback handler exits in factyour display may hang completely during long-running handlers if not manually updated (and handlers are not run in threadsas described in the next section)the window won' even redraw itself until the handler returns if covered and uncovered by another for instanceprograms that animate by repeatedly moving an object and pausing must call for an update before the end of the animation or only the final object position will appear on-screenworsethe gui will be completely inactive until the animation callback returns (see the simple animation examples later in this as well as pydraw in widget update_idletasks(this tool processes any pending idle events this may sometimes be safer than afterwhich has the potential to set up race (loopingconditions in some scenarios tk widgets use idle events to display themselves _tkinter createfilehandler(filemaskfunctionthis tool schedules the function to be called when file' status changes the function may be invoked when the file has data for readingis available for writingor triggers an exception the file argument is python file or socket object (technicallyanything with fileno(methodor an integer file descriptormask is tkinter readable or tkinter writable to specify the modeand the callback function takes two arguments--the file ready to converse and mask file handlers are often used to process pipes or socketssince normal input/output requests can block the caller because this call is not available on windowsit won' be used in this book since it' currently unix-only alternativeportable guis may be better off using after timer loops to poll for data and spawning threads to read data and place it on queues if needed--see for more details threads are much more general solution to nonblocking data transfers time toolsthreadsand animation
5,154
widget wait_window(winwidget wait_visibility(winthese tools pause the caller until tkinter variable changes its valuea window is destroyedor window becomes visible all of these enter local event loopsuch that the application' mainloop continues to handle events note that var is tkinter variable object (discussed earlier)not simple python variable to use for modal dialogsfirst call widget focus((to set input focusand widget grab((to make window be the only one activealthough we'll put some of these to work in exampleswe won' go into exhaustive details on all of these tools heresee other tk and tkinter documentation for more information using threads with tkinter guis keep in mind that for many programspython' thread support that we discussed in can serve some of the same roles as the tkinter tools listed in the preceding section and can even make use of them for instanceto avoid blocking gui (and its usersduring long-running file or socket transferthe transfer can simply be run in spawned threadwhile the rest of the program continues to run normally similarlyguis that must watch for inputs on pipes or sockets can do so in spawned threads or after callbacksor some combination thereofwithout blocking the gui itself if you do use threads in tkinter programshoweveryou need to remember that only the main thread (the one that built the gui and started the mainloopshould generally make gui calls at the leastmultiple threads should not attempt to update the gui at the same time for examplethe update method described in the preceding section has historically caused problems in threaded guis--if spawned thread calls this method (or calls method that does)it can sometimes trigger very strange and even spectacular program crashes in factfor simple and more vivid example of the lack of thread safety in tkinter guissee and run the following files in the book examples distribution package\pp \gui\tour\threads-demoall-frm py \pp \gui\tour threads-demoall-win py these scripts are takeoffs of the prior examples - and - which run the construction of four gui demo components in parallel threads they also both crash horrifically on windows and require forced shutdown of the program while some gui operations appear to be safe to perform in parallel threads ( see the canvas moves in example - )thread safety is not guaranteed by tkinter in general (for further proof of tkinter' lack of thread safetysee the discussion of threaded update loops in the next just after example - thread there that attempts to pop up new window also makes the gui fail resoundingly tkinter tourpart
5,155
constraints on programs for examplebecause spawned threads cannot usually perform gui processingthey must generally communicate with the main thread using global variables or shared mutable objects such as queuesas required by the application spawned thread which watches socket for datafor instancemight simply set global variables or append to shared queueswhich in turn triggers gui changes in the main thread' periodic after event callbacks the main thread' timer events process the spawned thread' results although some gui operations or toolkits may support multiple threads better than othersgui programs are generally best structured as main gui thread and non-gui "workerthreads this wayboth to avoid potential collisions and to finesse the thread safety issue altogether the pymailgui example later in the bookfor instancewill collect and dispatch callbacks produced by threads and stored on queue also remember that irrespective of thread safety of the gui itselfthreaded gui programs must follow the same principles of threaded programs in general--as we learned in such programs must still synchronize access to mutable state shared between threadsif it may be changed by threads running in parallel although producer/consumer thread model based upon queues can alleviate many thread issues for the gui itselfa program that spawns non-gui threads to update shared information used by the gui thread may still need to use thread locks to avoid concurrent update issues we'll explore gui threading in more detail in and we'll meet more realistic threaded gui programs in part ivespecially in ' pymailgui the latterfor instanceruns long-running tasks in threads to avoid blocking the guibut both restricts gui updates to the main thread and uses locks to prevent overlap of operations that may change shared caches using the after method of all the event tools in the preceding listthe after method may be the most interesting it allows scripts to schedule callback handler to be run at some time in the future though simple devicewe'll use this often in later examples in this book for instancein we'll meet clock program that uses after to wake up times per second and check for new timeand we'll see an image slideshow program that uses after to schedule the next photo display (see pyclock and pyviewto illustrate the basics of scheduled callbacksexample - does something bit different example - pp \gui\tour\alarm py flash and beep every second using after(callback loop from tkinter import class alarm(frame)time toolsthreadsand animation
5,156
default second frame __init__(selfself msecs msecs self pack(stopper button(selftext='stop the beeps!'command=self quitstopper pack(stopper config(bg='navy'fg='white'bd= self stopper stopper self repeater(def repeater(self)self bell(self stopper flash(self after(self msecsself repeateron every millisecs beep now flash button now reschedule handler if __name__ ='__main__'alarm(msecs= mainloop(this script builds the window in figure - and periodically calls both the button widget' flash method to make the button flash momentarily (it alternates colors quicklyand the tkinter bell method to call your system' sound interface the repeater method beeps and flashes once and schedules callback to be invoked after specific amount of time with the after method figure - stop the beepsbut after doesn' pause the callercallbacks are scheduled to occur in the backgroundwhile the program performs other processing--technicallyas soon as the tk event loop is able to notice the time rollover to make this workrepeater calls after each time throughto reschedule the callback delayed events are one-shot callbacksto repeat the event as loopwe need to reschedule it anew the net effect is that when this script runsit starts beeping and flashing once its onebutton window pops up and it keeps beeping and flashing and beeping and flashing other activities and gui operations don' affect it even if the window is iconifiedthe beeping continuesbecause tkinter timer events fire in the background you need to kill the window or press the button to stop the alarm by changing the msecs delayyou can make this beep as fast or as slow as your system allows (some platforms can' beep as fast as others this may or may not be the best demo to launch in crowded officebut at least you've been warned tkinter tourpart
5,157
the button flash method flashes the widgetbut it' easy to dynamically change other appearance options of widgetssuch as buttonslabelsand textwith the widget config method for instanceyou can also achieve flash-like effect by manually reversing foreground and background colors with the widget config method in scheduled after callbacks largely for funexample - specializes the alarm to go step further example - pp \gui\tour\alarm-hide py customize to erase or show button on after(timer callbacks from tkinter import import alarm class alarm(alarm alarm)def __init__(selfmsecs= )self shown false alarm alarm __init__(selfmsecsdef repeater(self)self bell(if self shownself stopper pack_forget(elseself stopper pack(self shown not self shown self after(self msecsself repeaterchange alarm callback default second on every millisecs beep now hide or erase button now or reverse colorsflash toggle state for next time reschedule handler if __name__ ='__main__'alarm(msecs= mainloop(when this script is runthe same window appearsbut the button is erased or redrawn on alternating timer events the widget pack_forget method erases (unmapsa drawn widget and pack makes it show up againgrid_forget and grid similarly hide and show widgets in grid the pack_forget method is useful for dynamically drawing and changing running gui for instanceyou can be selective about which components are displayedand you can build widgets ahead of time and show them only as needed hereit just means that users must press the button while it' displayedor else the noise keeps going example - goes even further there are handful of methods for hiding and unhiding entire top-level windowsto hide and unhide the entire window instead of just one widget within ituse the top-level window widget withdraw and deiconify methods the withdraw methoddemonstrated in example - completely erases the window and its icon (use iconify if you want the window' icon to appear during hidethe lift method raises window above all its siblings or relative to another you pass in this method is also known as tkraisebut not raise--its name in tk-because raise is reserved word in python time toolsthreadsand animation
5,158
normaliconiczoomed (full screen)or withdrawn experiment with these methods on your own to see how they differ they are also useful to pop up prebuilt dialog windows dynamicallybut are perhaps less practical here example - pp \gui\tour\alarm-withdraw py samebut hide or show entire window on after(timer callbacks from tkinter import import alarm class alarm(alarm alarm)def repeater(self)self bell(if self master state(='normal'self master withdraw(elseself master deiconify(self master lift(self after(self msecsself repeateron every millisecs beep now is window displayedhide entire windowno icon iconify shrinks to an icon else redraw entire window and raise above others reschedule handler if __name__ ='__main__'alarm(mainloop(master default tk root this works the samebut the entire window appears or disappears on beeps--you have to press it when it' shown you could add lots of other effects to the alarmand their timer-based callbacks technique is widely applicable whether your buttons and windows should flash and disappearthoughprobably depends less on tkinter technology than on your userspatience simple animation techniques apart from the direct shape moves of the canvasdraw example we met earlier in this all of the guis presented so far in this part of the book have been fairly static this last section shows you how to change thatby adding simple shape movement animations to the canvas drawing example listed in example - it also demonstrates and expands on the notion of canvas tags--the move operations performed here move all canvas objects associated with tag at once all oval shapes move if you press " ,and all rectangles move if you press " "as mentioned earliercanvas operation methods accept both object ids and tag names but the main goal here is to illustrate simple animation techniques using the time-based tools described earlier in this section there are three basic ways to move objects around canvasby loops that use time sleep to pause for fractions of second between multiple move operationsalong with manual update calls the script movessleepsmoves bit moreand so on time sleep call pauses the caller and so fails to return tkinter tourpart
5,159
deferred because of thatcanvas update must be called to redraw the screen after each moveor else updates don' appear until the entire movement loop callback finishes and returns this is classic long-running callback scenariowithout manual update callsno new gui events are handled until the callback returns in this scheme (including both new user requests and basic window redrawsby using the widget after method to schedule multiple move operations to occur every few milliseconds because this approach is based upon scheduled events dispatched by tkinter to your handlersit allows multiple moves to occur in parallel and doesn' require canvas update calls you rely on the event loop to run movesso there' no reason for sleep pausesand the gui is not blocked while moves are in progress by using threads to run multiple copies of the time sleep pausing loops of the first approach because threads run in parallela sleep in any thread blocks neither the gui nor other motion threads as described earlierguis should not be updated from spawned threads in generalbut some canvas calls such as move seem to be thread-safe today in the current tkinter implementation of these three schemesthe first yields the smoothest animations but makes other operations sluggish during movementthe second seems to yield slower motion than the others but is safer than using threads in generaland the second and third allow multiple objects to be in motion at the same time using time sleep loops the next three sections demonstrate the code structure of all three approaches in turnwith new subclasses of the canvasdraw example we met in example - earlier in this refer back to that example for its other event bindings and basic drawmoveand clear operationsherewe customize its object creators for tags and add new event bindings and actions example - illustrates the first approach example - pp \gui\tour\canvasdraw_tags py ""add tagged moves with time sleep (not widget after or threads)time sleep does not block the gui event loop while pausingbut screen not redrawn until callback returns or widget update callcurrently running onmove callback has exclusive attention until it returnsothers pause if press 'ror 'oduring move""from tkinter import import canvasdrawtime class canvaseventsdemo(canvasdraw canvaseventsdemo)def __init__(selfparent=none)canvasdraw canvaseventsdemo __init__(selfparentself canvas create_text( text='press and to move shapes'self canvas master bind(''self onmoveovalstime toolsthreadsand animation
5,160
self kinds self create_oval_taggedself create_rectangle_tagged def create_oval_tagged(selfx )objectid self canvas create_oval( self canvas itemconfig(objectidtag='ovals'fill='blue'return objectid def create_rectangle_tagged(selfx )objectid self canvas create_rectangle( self canvas itemconfig(objectidtag='rectangles'fill='red'return objectid def onmoveovals(selfevent)print('moving ovals'self moveinsquares(tag='ovals'move all tagged ovals def onmoverectangles(selfevent)print('moving rectangles'self moveinsquares(tag='rectangles'def moveinsquares(selftag) reps of times per sec for in range( )for (diffxdiffyin [(+ )( + )(- )( - )]self canvas move(tagdiffxdiffyself canvas update(force screen redraw/update time sleep( pausebut don' block gui if __name__ ='__main__'canvaseventsdemo(mainloop(all three of the scripts in this section create window of blue ovals and red rectangles as you drag new shapes out with the left mouse button the drag-out implementation itself is inherited from the superclass right-mouse-button click still moves single shape immediatelyand double-left click still clears the canvastoo--other operations inherited from the original superclass in factall this new script really does is change the object creation calls to add tags and colors to drawn objects hereadd text field at the top of the canvasand add bindings and callbacks for motion requests figure - shows what this subclass' window looks like after dragging out few shapes to be animated the "oand "rkeys are set up to start animation of all the ovals and rectangles you've drawnrespectively pressing " ,for examplemakes all the blue ovals start moving synchronously objects are animated to mark out five squares around their location and to move four times per second new objects drawn while others are in motion start to movetoobecause they are tagged you need to run these live to get feel for the simple animations they implementof course (you could try moving this book back and forth and up and downbut it' not quite the sameand might look silly in public places tkinter tourpart
5,161
using widget after events the main drawback of this first approach is that only one animation can be going at onceif you press "ror "owhile move is in progressthe new request puts the prior movement on hold until it finishes because each move callback handler assumes the only thread of control while it runs that isonly one time sleep loop callback can be running at timeand new one started by an update call is effectively recursive call which pauses another loop already in progress screen updates are bit sluggish while moves are in progresstoobecause they happen only as often as manual update calls are made (try drag-out or cover/uncover of the window during move to see for yourselfin factuncommenting the canvas update call in example - makes the gui completely unresponsive during the move--it won' redraw itself if covereddoesn' respond to new user requestsand doesn' show any of its progress (you only get to see the final statethis effectively simulates the impact of long-running operations on guis in general example - specializes just the moveinsquares method of the prior example to remove all such limitations--by using after timer callback loopsit schedules moves without potential pauses it also reflects the most common (and likely bestway that tkinter guis handle time-based events at large by breaking tasks into parts this way instead of running them all at oncethey are naturally both distributed over time and overlapped time toolsthreadsand animation
5,162
""similarbut with widget after(scheduled eventsnot time sleep loopsbecause these are scheduled eventsthis allows both ovals and rectangles to be moving at the _same_ time and does not require update calls to refresh the guithe motion gets wild if you press 'oor 'rwhile move in progressmultiple move updates start firing around the same time""from tkinter import import canvasdraw_tags class canvaseventsdemo(canvasdraw_tags canvaseventsdemo)def moveem(selftagmoremoves)(diffxdiffy)moremoves moremoves[ ]moremoves[ :self canvas move(tagdiffxdiffyif moremovesself canvas after( self moveemtagmoremovesdef moveinsquares(selftag)allmoves [(+ )( + )(- )( - ) self moveem(tagallmovesif __name__ ='__main__'canvaseventsdemo(mainloop(this version inherits the drawing customizations of the priorbut lets you make both ovals and rectangles move at the same time--drag out few ovals and rectanglesand then press "oand then "rright away to make this go in facttry pressing both keys few timesthe more you pressthe more the objects movebecause multiple scheduled events are firing and moving objects from wherever they happen to be positioned if you drag out new shape during moveit starts moving immediately as before using multiple time sleep loop threads running animations in threads can sometimes achieve the same effect as discussed earlierit can be dangerous to update the screen from spawned thread in generalbut it works in this example (on the test platform usedat leastexample - runs each animation task as an independent and parallel thread that iseach time you press the "oor "rkey to start an animationa new thread is spawned to do the work example - pp \gui\tour\canvasdraw_tags_thread py ""similarbut run time sleep loops in parallel with threadsnot after(events or single active time sleep loopbecause threads run in parallelthis also allows ovals and rectangles to be moving at the _same_ time and does not require update calls to refresh the guiin factcalling update(once made this crash badlythough some canvas calls must be thread safe or this wouldn' work at all"" tkinter tourpart
5,163
import canvasdraw_tags import _threadtime class canvaseventsdemo(canvasdraw_tags canvaseventsdemo)def moveem(selftag)for in range( )for (diffxdiffyin [(+ )( + )(- )( - )]self canvas move(tagdiffxdiffytime sleep( pause this thread only def moveinsquares(selftag)_thread start_new_thread(self moveem(tag,)if __name__ ='__main__'canvaseventsdemo(mainloop(this version lets you move shapes at the same timejust like example - but this time it' reflection of threads running in parallel in factthis uses the same scheme as the first time sleep version herethoughthere is more than one active thread of controlso move handlers can overlap in time--time sleep blocks only the calling threadnot the program at large this example works on windows todaybut it failed on linux at one point in this book' lifetime--the screen was not updated as threads changed itso you couldn' see any changes until later gui events the usual rule of thumb about avoiding gui updates in spawned threads laid out earlier still holds true it is usually safer to have your threads do number crunching only and let the main thread (the one that built the guihandle any screen updates even under this modelthoughthe main thread can still use after event loops like that of example - to watch for results from worker threads to appear without being blocked while waiting (more on this in the next section and parts of this story are implementation details prone to change over timeand it' not impossible that gui updates in threads may be better supported by tkinter in the futureso be sure to explore the state of threading in future releases for more details other animation topics we'll revisit animation in ' pydraw examplethereall three of the techniques we just met--sleepstimersand threads--will be resurrected to move shapestextand photos to arbitrary spots on canvas marked with mouse click and although the canvas widget' absolute coordinate system makes it the workhorse of most nontrivial animationstkinter animation in general is limited mostly by your imagination in closinghere are few more words on the topic to hint at the possibilities time toolsthreadsand animation
5,164
besides canvas-based animationswidget configuration tools support variety of animation effects for exampleas we saw in the flashing and hiding alarm scripts earlier (see example - )it is also easy to change the appearance of other kinds of widgets dynamically with after timer-event loops with timer-based loopsyou can periodically flash widgetscompletely erase and redraw widgets and windows on the flyreverse or change widget colorsand so on see "for good time on page for another example in this category which changes fonts and colors on the fly (albeitwith questionable ergonomic intentionsthreads and animation techniques for running long-running tasks in parallel threads become more important if animations must remain active while your program waits for instanceimagine program that spends minutes downloading data from networkcalculating the output of numeric modelor performing other long-running tasks if such program' gui must display an animation or otherwise show progress while waiting for the taskit can do so by either altering widget' appearance or by moving objects in canvas periodically--simply use the after method to wake up intermittently to modify the gui as we've seen progress bar or counterfor instancemay be updated during after timer-event handling in additionthoughthe long-running task itself will likely have to be run in spawned parallel thread so that your gui remains active and performs the animation during the wait otherwiseno gui updates will occur until the task returns control to the gui during after timer-event processingthe main gui thread might check variables or objects set by the long-running task' thread to determine completion or progress especially if more than one long-running task may be active at the same timethe spawned thread might also communicate with the gui thread by storing information in python queue objectto be picked up and handled by the gui during after events for generalitythe queue might even contain function objects that are run by the gui to update the display againwe'll study such threaded gui programming and communication techniques in and employ them in the pymailgui example later in the book for nowkeep in mind that spawning computational tasks in threads can allow the gui itself to both perform animations and remain active in general during wait states graphics and gaming toolkits unless you stopped playing video games shortly after the ascent of pongyou probably also know that the sorts of movement and animation techniques shown in this and book are suitable for some simple game-like programsbut not all for more demanding taskspython also has additional graphics and gaming support we haven' studied here tkinter tourpart
5,165
package for common animation and movie file formats such as fli and mpeg other third-party toolkits such as openglblenderpygamemayaand vpython provide even higher-level graphics and animation toolkits the pyopengl system also offers tk support for guis see the pypi websites for links or search the web if you're interest in gaming specificallypygame and other packages support game development in pythonand other books and web resources focus on this topic although python is not widely used as the sole implementation language of graphicsintensive game programsit is used as both prototyping and scripting language for such products +when integrated with graphics librariesit can serve even broader roles see the end of the tour and that' wrap for our tour of the tkinter library you've now seen all the core widgets and tools previewed in (flip back for summary of territory covered on this tourfor more detailswatch for all of the tools introduced here to appear again in the advanced gui techniques in the larger gui examples in and the remainder of the book at large to some extentthe last few have laid the groundwork needed to step up to the larger programs that follow other widgets and options should point outthoughthat this story is still not quite complete although we've covered the entire basic tkinter widget arsenal and mastered gui fundamentals along the waywe've skipped handful of newer and more advanced widgets introduced to tkinter recentlyspinbox an entry used to select among set or range of values labelframe frame with border and title around group of items panedwindow geometry manager widget containing multiple widgets that can be resized by moving separator lines with the mouse +perhaps most prominently todaythe popular eve online game uses python for scripting and much of the functionality--both on the server and the client it uses the stackless python implementation to boost massively parallel multitasking responsiveness other notable game companies using python include the makers of civilization ivand the now-defunct origin systems (at last reportits game ultima online ii was to use python for scripting its animationthe end of the tour
5,166
popular pmwtixor ttk extension packages for tkinter (described in or any other third-party packages in general for instancetix and ttk both provide additional widget options outlined in which are now part of python' standard library the third-party domain tends to change over timebut has hosted tree widgetshtml viewersfont selection dialogstablesand much more for tkinterand includes the pmw megawidget set many tkinter programs such as python' standard idle development gui include font dialogstree widgetsand more that you may be able to use in your own applications because such extensions are too complex for us to cover in useful fashion herethoughwe'll defer to other resources in the interest of space to sample richer options for your gui scriptsbe sure to consult tkintertktixttkand pmw documentation for more details on additional widgetsand visit the pypi website at or search the web for other third-party tkinter extensions should also mention that there are more widget configuration options than we have met on this tour consult tk and tkinter resources for options not listed explicitly here although other tkinter tools are analogous to those presented herethe space have for illustrating additional widgets and options in this book is limited by both my publisher and the finite nature of trees tkinter tourpart
5,167
gui coding techniques "building better mousetrapthis continues our look at building guis with python and the tkinter library by presenting collection of more advanced gui programming patterns and techniques in the preceding three we explored all the fundamentals of tkinter itself hereour goal is to put them to work to add higher-level structures that will be useful in larger programs that isour focus shifts here to writing code of our own which implements utility above and beyond the basic tkinter toolkit--utility that we'll actually find useful in more complete examples later in the book some of the techniques we will be studying in this are as followsproviding common gui operations in "mixinclasses building menus and toolbars from data structure templates adding gui interfaces to command-line tools redirecting input and output streams to gui widgets reloading gui callback handlers on the fly wrapping up and automating top-level window interfaces using threads and queues to avoiding blocking in guis popping up gui windows on demand from non-gui programs adding guis as separate programs with sockets and pipes as with other in this bookthis has dual agenda--not only will we be studying gui programmingbut we'll also be learning more about general python development concepts such as object-oriented programming (oopand code reuse as we'll seeby coding gui tools in pythonit' easy to apply them in wide variety of contexts and programs as segue to the next this one also closes with look at the pydemos and pygadgets launcher toolbars--guis used to start larger gui examples although most
5,168
you study them in the examples distribution package two notes before we beginfirstbe sure to read the code listings in this for details we won' present in the narrative secondalthough small examples that apply in this techniques will show up along the waymore realistic application will have to await more realistic programs we'll put these techniques to use in the larger examples in the next and throughout the rest of the book in factwe'll be reusing the modules we develop here oftenas tools in other programs in this bookreusable software wants to be reused firstthoughlet' do what our species does best and build some tools guimixincommon tool mixin classes if you read the last three you probably noticed that the code used to construct nontrivial guis can become long if we make each widget by hand not only do we have to link up all the widgets manuallybut we also need to remember and then set dozens of options if we stick to this strategygui programming often becomes an exercise in typingor at least in cut-and-paste text editor operations widget builder functions instead of performing each step by handa better idea is to wrap or automate as much of the gui construction process as possible one approach is to code functions that provide typical widget configurationsand automate the construction process for cases to which they apply for instancewe could define button function to handle configuration and packing details and support most of the buttons we draw example - provides handful of such widget builder calls example - pp \gui\tools\widgets py ""##############################################################################wrap up widget construction in functions for easier usebased upon some assumptions ( expansion)use **extras fkw args for widthfont/coloretc and repack result manually later to override defaults if needed##############################################################################""from tkinter import def frame(rootside=top**extras)widget frame(rootwidget pack(side=sideexpand=yesfill=bothif extraswidget config(**extrasreturn widget gui coding techniques
5,169
widget label(roottext=textrelief=ridgewidget pack(side=sideexpand=yesfill=bothif extraswidget config(**extrasreturn widget default config pack automatically apply any extras def button(rootsidetextcommand**extras)widget button(roottext=textcommand=commandwidget pack(side=sideexpand=yesfill=bothif extraswidget config(**extrasreturn widget def entry(rootsidelinkvar**extras)widget entry(rootrelief=sunkentextvariable=linkvarwidget pack(side=sideexpand=yesfill=bothif extraswidget config(**extrasreturn widget if __name__ ='__main__'app tk(frm frame(apptopmuch less code required herelabel(frmleft'spam'button(frmbottom'press'lambdaprint('pushed')mainloop(this module makes some assumptions about its clientsuse caseswhich allows it to automate typical construction chores such as packing the net effect is to reduce the amount of code required of its importers when run as scriptexample - creates simple window with ridged label on the left and button on the right that prints message when pressedboth of which expand along with the window run this on your own for lookits window isn' really anything new for usand its code is meant more as library than script--as we'll see when we make use of it later in ' pycalc this function-based approach can cut down on the amount of code required as functionsthoughits tools don' lend themselves to customization in the broader oop sense moreoverbecause they are not methodsthey do not have access to the state of an object representing the gui mixin utility classes alternativelywe can implement common methods in class and inherit them everywhere they are needed such classes are commonly called mixin classes because their methods are "mixed inwith other classes mixins serve to package generally useful tools as methods the concept is almost like importing modulebut mixin classes can access the subject instanceselfto utilize both per-instance state and inherited methods the script in example - shows how guimixincommon tool mixin classes
5,170
""############################################################################## "mixinclass for other framescommon methods for canned dialogsspawning programssimple text viewersetcthis class must be mixed with frame (or subclass derived from framefor its quit method ##############################################################################""from tkinter import from tkinter messagebox import from tkinter filedialog import from pp gui tour scrolledtext import scrolledtext from pp launchmodes import portablelaunchersystem or tkinter scrolledtext or use multiprocessing class guimixindef infobox(selftitletext*args)return showinfo(titletextuse standard dialogs *args for bkwd compat def errorbox(selftext)showerror('error!'textdef question(selftitletext*args)return askyesno(titletextreturn true or false def notdone(self)showerror('not implemented''option not available'def quit(self)ans self question('verify quit''are you sure you want to quit?'if ansframe quit(selfquit not recursivedef help(self)self infobox('rtfm''see figure 'override this better def selectopenfile(selffile=""dir=")use standard dialogs return askopenfilename(initialdir=dirinitialfile=filedef selectsavefile(selffile=""dir=")return asksaveasfilename(initialfile=fileinitialdir=dirdef clone(selfargs=())new toplevel(myclass self __class__ myclass(new*argsoptional constructor args make new in-process version of me instance' (lowestclass object attach/run instance to new window def spawn(selfpycmdlinewait=false)if not waitportablelauncher(pycmdlinepycmdline)(elsesystem(pycmdlinepycmdline)(def browser(selffilename)new toplevel( gui coding techniques start new process run python progam wait for it to exit make new window
5,171
text with scrollbar view text config(height= width= config text in frame view text config(font=('courier' 'normal')use fixed-width font new title("text viewer"set window mgr attrs new iconname("browser"file text added auto ""def browser(selffilename)new toplevel(text scrolledtext(newheight= width= text config(font=('courier' 'normal')text pack(expand=yesfill=bothnew title("text viewer"new iconname("browser"text insert(' 'open(filename' 'read(""if tkinter scrolledtext included for reference if __name__ ='__main__'class testmixin(guimixinframe)standalone test def __init__(selfparent=none)frame __init__(selfparentself pack(button(selftext='quit'command=self quitpack(fill=xbutton(selftext='help'command=self helppack(fill=xbutton(selftext='clone'command=self clonepack(fill=xbutton(selftext='spawn'command=self otherpack(fill=xdef other(self)self spawn('guimixin py'spawn self as separate process testmixin(mainloop(although example - is geared toward guisit' really about design concepts the guimixin class implements common operations with standard interfaces that are immune to changes in implementation in factthe implementations of some of this class' methods did change--between the first and second editions of this bookold-style dialog calls were replaced with the new tk standard dialog callsin the fourth editionthe file browser was updated to use different scrolled text class because this class' interface hides such detailsits clients did not have to be changed to use the new techniques as isguimixin provides methods for common dialogswindow cloningprogram spawningtext file browsingand so on we can add more methods to such mixin later if we find ourselves coding the same methods repeatedlythey will all become available immediately everywhere this class is imported and mixed moreovergui mixin' methods can be inherited and used as isor they can be redefined in subclasses such are the natural advantages of classes over functions guimixincommon tool mixin classes
5,172
the quit method serves some of the same purpose as the reusable quitter button we used in earlier because mixin classes can define large library of reusable methodsthey can be more powerful way to package reusable components than individual classes if the mixin is packaged wellwe can get lot more from it than single button' callback the clone method makes new in-process copyin new top-level windowof the most specific class that mixes in guimixin (self __class__ is the class object that the instance was created fromassuming that the class requires no constructor arguments other than parent containerthis opens new independent copy of the window (pass in any extra constructor arguments requiredthe browser method opens the scrolledtext object we wrote in in new window and fills it with the text of file to be viewed as noted in the preceding there is also scrolledtext widget in standard library module tkinter scrolledtextbut its interface differsit does not load file automaticallyand it is prone to becoming deprecated (though it hasn' over many yearsfor referenceits alternative code is included the spawn method launches python program command line as new independent process and waits for it to end or not (depending on the default false wait argument--guis usually shouldn' waitthis method is simplethoughbecause we wrapped launching details in the launchmodes module presented at the end of guimixin both fosters and practices good code reuse habits the guimixin class is meant to be library of reusable tool methods and is essentially useless by itself in factit must generally be mixed with frame-based class to be usedquit assumes it' mixed with frameand clone assumes it' mixed with widget class to satisfy such constraintsthis module' self-test code at the bottom combines gui mixin with frame widget figure - shows the scene created by the module' self-test after pressing "cloneand "spawnonce eachand then "helpin one of the three copies because they are separate processeswindows started with "spawnkeep running after other windows are closed and do not impact other windows when closed themselvesa "clonewindow is inprocess instead--it is closed with othersbut its "xdestroys just itself make sure your pythonpath includes the pp directory' container for the cross-directory package imports in this example and later examples which use it we'll see guimixin show up again as mixin in later examplesthat' the whole point of code reuseafter all although functions are often usefulclasses support inheritance and access to instance stateand provide an extra organizational structure--features that are especially useful given the coding requirements of guis for instancemany of guimixin' methods could be replaced with simple functionsbut clone and quit could not the next section carries these talents of mixin classes even further gui coding techniques
5,173
guimakerautomating menus and toolbars the last section' mixin class makes common tasks simplerbut it still doesn' address the complexity of linking up widgets such as menus and toolbars of courseif we had access to gui layout tool that generates python codethis would not be an issueat least for some of the more static interfaces we may require we' design our widgets interactivelypress buttonand fill in the callback handler blanks especially for relatively simple toolkit like tkinterthougha programming-based approach can often work just as well we' like to be able to inherit something that does all the grunt work of construction for usgiven template for the menus and toolbars in window here' one way it can be done--using trees of simple objects the class in example - interprets data structure representations of menus and toolbars and builds all the widgets automatically example - pp \gui\tools\guimaker py ""##############################################################################an extended frame that makes window menus and toolbars automatically use guimakerframemenu for embedded components (makes frame-based menususe guimakerwindowmenu for top-level windows (makes tk window menussee the self-test code (and pyeditfor an example layout tree format ##############################################################################""import sys from tkinter import from tkinter messagebox import showinfo class guimaker(frame)menubar [widget classes class defaults guimakerautomating menus and toolbars
5,174
[helpbutton true def __init__(selfparent=none)frame __init__(selfparentself pack(expand=yesfill=bothself start(self makemenubar(self maketoolbar(self makewidgets(change per instance in subclasses set these in start(if need self make frame stretchable for subclassset menu/toolbar done herebuild menu bar done herebuild toolbar for subclassadd middle part def makemenubar(self)""make menu bar at the top (tk menus belowexpand=nofill= so same width on resize ""menubar frame(selfrelief=raisedbd= menubar pack(side=topfill=xfor (namekeyitemsin self menubarmbutton menubutton(menubartext=nameunderline=keymbutton pack(side=leftpulldown menu(mbuttonself addmenuitems(pulldownitemsmbutton config(menu=pulldownif self helpbuttonbutton(menubartext 'help'cursor 'gumby'relief flatcommand self helppack(side=rightdef addmenuitems(selfmenuitems)for item in itemsscan nested items list if item ='separator'stringadd separator menu add_separator({}elif type(item=listlistdisabled item list for num in itemmenu entryconfig(numstate=disabledelif type(item[ ]!listmenu add_command(label item[ ]commandunderline item[ ]add command command item[ ]cmd=callable elsepullover menu(menuself addmenuitems(pulloveritem[ ]sublistmenu add_cascade(label item[ ]make submenu underline item[ ]add cascade menu pulloverdef maketoolbar(self)""make button bar at bottomif any expand=nofill= so same width on resize this could support images toosee gui coding techniques
5,175
""if self toolbartoolbar frame(selfcursor='hand 'relief=sunkenbd= toolbar pack(side=bottomfill=xfor (nameactionwherein self toolbarbutton(toolbartext=namecommand=actionpack(wheredef makewidgets(self)""make 'middlepart lastso menu/toolbar is always on top/bottom and clipped lastoverride this defaultpack middle any sidefor gridgrid middle part in packed frame ""name label(selfwidth= height= relief=sunkenbg='white'text self __class__ __name__cursor 'crosshair'name pack(expand=yesfill=bothside=topdef help(self)"override me in subclassshowinfo('help''sorryno help for self __class__ __name__def start(self)"override me in subclassset menu/toolbar with selfpass ##############################################################################customize for tk main window menu barinstead of frame ##############################################################################guimakerframemenu guimaker use this for embedded component menus class guimakerwindowmenu(guimaker)use this for top-level window menus def makemenubar(self)menubar menu(self masterself master config(menu=menubarfor (namekeyitemsin self menubarpulldown menu(menubarself addmenuitems(pulldownitemsmenubar add_cascade(label=nameunderline=keymenu=pulldownif self helpbuttonif sys platform[: ='win'menubar add_command(label='help'command=self helpelsepulldown menu(menubarlinux needs real pull down pulldown add_command(label='about'command=self helpmenubar add_cascade(label='help'menu=pulldownguimakerautomating menus and toolbars
5,176
self-test when file run standalone'python guimaker py##############################################################################if __name__ ='__main__'from guimixin import guimixin mix in help method menubar ('file' [('open' lambda: )lambda: is no-op ('quit' sys exit)])use sysno self here ('edit' [('cut' lambda: )('paste' lambda: )]toolbar [('quit'sys exit{'side'left})class testappframemenu(guimixinguimakerframemenu)def start(self)self menubar menubar self toolbar toolbar class testappwindowmenu(guimixinguimakerwindowmenu)def start(self)self menubar menubar self toolbar toolbar class testappwindowmenubasic(guimakerwindowmenu)def start(self)self menubar menubar self toolbar toolbar guimaker helpnot guimixin root tk(testappframemenu(toplevel()testappwindowmenu(toplevel()testappwindowmenubasic(rootroot mainloop(to make sense of this moduleyou have to be familiar with the menu fundamentals introduced in if you arethoughit' straightforward--the guimaker class simply traverses the menu and toolbar structures and builds menu and toolbar widgets along the way this module' self-test code includes simple example of the data structures used to lay out menus and toolbarsmenu bar templates lists and nested sublists of (labelunderlinehandlertriples if handler is sublist rather than function or methodit is assumed to be cascading submenu toolbar templates list of (labelhandlerpack-optionstriples pack-options is coded as dictionary of options passed on to the widget pack methodwe can code these as {' ':vliteralsor with the dict( =vcall' keyword syntax pack accepts dictionary argumentbut we could also transform the dictionary into individual keyword gui coding techniques
5,177
to be textbut images could be supported too (see the note under "bigguia client demo programon page for varietythe mouse cursor changes based upon its locationa hand in the toolbarcrosshairs in the default middle partand something else over help buttons of framebased menus (customize as desiredsubclass protocols in addition to menu and toolbar layoutsclients of this class can also tap into and customize the method and geometry protocols the class implementstemplate attributes clients of this class are expected to set menubar and toolbar attributes somewhere in the inheritance chain by the time the start method has finished initialization the start method can be overridden to construct menu and toolbar templates dynamicallysince self is available when it is calledstart is also where general initializations should be performed--guimixin' __init__ constructor must be runnot overridden adding widgets the makewidgets method can be redefined to construct the middle part of the window--the application portion between the menu bar and the toolbar by defaultmakewidgets adds label in the middle with the name of the most specific classbut this method is expected to be specialized packing protocol in specialized makewidgets methodclients may attach their middle portion' widgets to any side of self ( framesince the menu and toolbars have already claimed the container' top and bottom by the time makewidgets is run the middle part does not need to be nested frame if its parts are packed the menu and toolbars are also automatically packed first so that they are clipped last if the window shrinks gridding protocol the middle part can contain grid layoutas long as it is gridded in nested frame that is itself packed within the self parent (remember that each container level may use grid or packnot bothand that self is frame with already packed bars by the time makewidgets is called because the guimaker frame packs itself within its parentit is not directly embeddable in container with widgets arranged in gridfor similar reasonsadd an intermediate gridded frame to use it in this context guimakerautomating menus and toolbars
5,178
in return for conforming to guimaker protocols and templatesclient subclasses get frame that knows how to automatically build up its own menus and toolbars from template data structures if you read the preceding menu examplesyou probably know that this is big win in terms of reduced coding requirements gui maker is also clever enough to export interfaces for both menu styles that we met in guimakerwindowmenu implements tk -style top-level window menususeful for menus associated with standalone programs and pop ups guimakerframemenu implements alternative frame/menubutton-based menususeful for menus on objects embedded as components of larger gui both classes build toolbarsexport the same protocolsand expect to find the same template structuresthey differ only in the way they process menu templates in factone is simply subclass of the other with specialized menu maker method--only toplevel menu processing differs between the two styles ( menu with menu cascades rather than frame with menubuttonsguimaker self-test like guimixinwhen we run example - as top-level programwe trigger the selftest logic at the bottom of its filefigure - shows the windows we get three windows come uprepresenting each of the self-test code' testapp classes all three have menu and toolbar with the options specified in the template data structures created in the self-test codefile and edit menu pull downsplus quit toolbar button and standard help menu button in the screenshotone window' file menu has been torn off and the edit menu of another is being pulled downthe lower window was resized for effect guimaker can be mixed in with other superclassesbut it' primarily intended to serve the same extending and embedding roles as tkinter frame widget class (which makes sensegiven that it' really just customized frame with extra construction protocolsin factits self-test combines guimaker frame with the prior section' guimixin tools package class because of the superclass relationships codedtwo of the three windows get their help callback handler from guimixintestappwindowmenubasic gets guimaker' instead notice that the order in which these two classes are mixed can be importantbecause both guimixin and frame define quit methodwe need to list the class from which we want to get it first in the mixed class' header line due to the left-to-right search rule of multiple inheritance to select guimixin' methodsit should usually be listed before superclass derived from real widgets gui coding techniques
5,179
we'll put guimaker to more practical use in instances such as the pyedit example in the next section shows another way to use guimaker' templates to build up sophisticated interfaceand serves as another test of its functionality bigguia client demo program let' look at program that makes better use of the two automation classes we just wrote in the module in example - the hello class inherits from both guimixin and guimaker guimaker provides the link to the frame widgetplus the menu/toolbar construction logic guimixin provides extra common-behavior methods reallyhello is another kind of extended frame widget because it is derived from guimaker to get menu and toolbar for freeit simply follows the protocols defined by guimaker--it sets the menubar and toolbar attributes in its start methodand overrides makewidgets to put custom label in the middle example - pp \gui\tools\big_gui py ""gui demo implementation combines makermixinand this ""import sysos from tkinter import from pp gui tools guimixin import from pp gui tools guimaker import widget classes mix-in methodsquitspawnetc frameplus menu/toolbar builder guimakerautomating menus and toolbars
5,180
or guimakerframemenu def start(self)self hellos self master title("guimaker demo"self master iconname("guimaker"def spawnme()self spawn('big_gui py'defer call vs lambda self menubar ('file' [('new ' spawnme)('open ' self fileopen)('quit' self quit))('edit' [('cut'- self notdone)('paste'- self notdone)'separator'('stuff'- [('clone'- self clone)('more'- self more))('delete'- lambda: )[ ]) tree pull downs (pull-down[menu items listlabel,underline,action no underline|action lambda: works too add separator cascaded submenu disable 'delete('play' [('hello' self greeting)('popup ' self dialog)('demos' [('toplevels' lambdaself spawn( \tour\toplevel py'))('frames' lambdaself spawn( \tour\demoall-frm-ridge py'))('images' lambdaself spawn( \tour\buttonpics py'))('alarm' lambdaself spawn( \tour\alarm py'wait=false))('other '- self pickdemo)))self toolbar add buttons ('quit'self quitdict(side=right))or {'side'right('hello'self greetingdict(side=left))('popup'self dialogdict(side=leftexpand=yes)def makewidgets(self)override default middle label(selftext='hello maker world!'middle of window width= height= relief=sunkencursor='pencil'bg='white'middle pack(expand=yesfill=bothdef greeting(self)self hellos + gui coding techniques
5,181
print("hi"elseself infobox("three"'hello!'on every third press def dialog(self)button self question('oops!''you typed "rm*continue?''questhead'('yes''no')[lambdanoneself quit][button](old style args ignored def fileopen(self)pick self selectopenfile(file='big_gui py'if pickself browser(pickbrowse my source fileor other def more(self)new toplevel(label(newtext=' new non-modal window'pack(button(newtext='quit'command=self quitpack(side=leftbutton(newtext='more'command=self morepack(side=rightdef pickdemo(self)pick self selectopenfile(dir='if pickself spawn(pickspawn any python program if __name__ ='__main__'hello(mainloop(make onerun one this script lays out fairly large menu and toolbar structureand also adds callback methods of its own that print stdout messagespop up text file browsers and new windowsand run other programs many of the callbacks don' do much more than run the notdone method inherited from guimixinthoughthis code is intended mostly as guimaker and guimixin demo when big_gui is run as top-level programit creates window with four menu pull downs on top and three-button toolbar on the bottomshown in figure - along with some of the pop-up windows its callbacks create the menus have separatorsdisabled entriesand cascading submenusall as defined by the menubar template used by guimakerand quit invokes the verifying dialog inherited from guimixin--some of the many tools we're getting for free here figure - shows this script' window againafter its play pull down has been used to launch three independently running demos that we wrote in and these demos are ultimately started by using the portable launcher tools we wrote in and acquired from the guimixin class if you want to run other demos on your computerselect the play menu' other option to pop up standard file selection dialog instead and navigate to the desired program' file one notei copied the icon bitmap used by the top-levels demo in the play menu to this script' directorylaterwe'll write tools that attempt to locate one automatically guimakerautomating menus and toolbars
5,182
figure - big_gui with spawned demos finallyi should note that guimaker could be redesigned to use trees of embedded class instances that know how to apply themselves to the tkinter widget tree being constructedinstead of branching on the types of items in template data structures in the interest of spacethoughwe'll banish that extension to the land of suggested exercises in this edition gui coding techniques
5,183
which redefines its toolbar construction method would be both great way to experiment with the code and useful utility if added every cool feature imaginablethoughthis book could easily become big enough to be gravitationally significant shellguiguis for command-line tools demos are funbut to better show how things like the guimixin class can be of practical usewe need more realistic application here' onesuppose you've written set of command-line system administration scriptsalong the lines of those we studied in part ii as we sawsuch scripts work well from command linebut require you to remember all their options each time they are runif you're like methis usually implies having to pore over the source code after period of nonuse instead of requiring users of such tools (including yourselfto type cryptic commands at shellwhy not also provide an easy-to-use tkinter gui interface for running such programssuch gui can prompt for command-line inputsinstead of expecting users to remember them while we're at itwhy not generalize the whole notion of running command-line tools from guito make it easy to support future tools tooa generic shell-tools display examples - through - --seven filesspanning two command-line scriptsone gui utility moduletwo gui dialogsand main gui and its options specification module--comprise concrete implementation of these artificially rhetorical musings because want this to be general-purpose tool that can run any command-line programits design is factored into modules that become more application-specific as we go lower in the software hierarchy at the topthings are about as generic as they can beas shown in example - example - pp \gui\shellgui\shellgui py #!/usr/local/bin/python ""###############################################################################tools launcheruses guimaker templatesguimixin std quit dialogi am just class libraryrun mytools script to display the gui###############################################################################""from tkinter import from pp gui tools guimixin import guimixin from pp gui tools guimaker import get widgets get quitnot done menu/toolbar builder class shellgui(guimixinguimakerwindowmenu) frame maker mixins shellguiguis for command-line tools
5,184
self setmenubar(self settoolbar(self master title("shell tools listbox"self master iconname("shell tools"use guimaker if component def handlelist(selfevent)label self listbox get(activeself runcommand(labelon listbox double-click fetch selection text and call action here def makewidgets(self)add listbox in middle sbar scrollbar(selfcross link sbarlist list listbox(selfbg='white'or use tour scrolledlist sbar config(command=list yviewlist config(yscrollcommand=sbar setsbar pack(side=rightfill=ypack st=clip last list pack(side=leftexpand=yesfill=bothlist clipped first for (labelactionin self fetchcommands()add to listbox list insert(endlabeland menu/toolbars list bind(''self handlelistset event handler self listbox list def fortoolbar(selflabel)return true put on toolbardefault all def settoolbar(self)self toolbar [for (labelactionin self fetchcommands()if self fortoolbar(label)self toolbar append((labelactiondict(side=left))self toolbar append(('quit'self quitdict(side=right))def setmenubar(self)toolentries [self menubar ('file' [('quit'- self quit)])('tools' toolentriesfor (labelactionin self fetchcommands()toolentries append((label- action)pull-down name menu items list label,underline,action add app items to menu ###############################################################################delegate to template type-specific subclasses which delegate to app tool-set-specific subclasses ###############################################################################class listmenugui(shellgui)def fetchcommands(self)subclassset 'mymenureturn self mymenu list of (labelcallbackdef runcommand(selfcmd)for (labelactionin self mymenuif label =cmdaction(class dictmenugui(shellgui)def fetchcommands(self) gui coding techniques
5,185
def runcommand(selfcmd)self mymenu[cmd](the shellgui class in this module knows how to use the guimaker and guimixin interfaces to construct selection window that displays tool names in menusa scrolled listand toolbar it also provides fortoolbar method that you can override and that allows subclasses to specify which tools should and should not be added to the window' toolbar (the toolbar can become crowded in hurryhoweverit is deliberately ignorant about both the names of tools that should be displayed in those places and about the actions to be run when tool names are selected insteadshellgui relies on the listmenugui and dictmenugui subclasses in this file to provide list of tool names from fetchcommands method and dispatch actions by name in runcommand method these two subclasses really just serve to interface to application-specific tool sets laid out as lists or dictionariesthoughthey are still naive about what tool names really go up on the gui that' by designtoo--because the tool sets displayed are defined by lower subclasseswe can use shellgui to display variety of different tool sets application-specific tool set classes to get to the actual tool setswe need to go one level down the module in example - defines subclasses of the two type-specific shellgui classesto provide sets of available tools in both list and dictionary formats (you would normally need only onebut this module is meant for illustrationthis is also the module that is actually run to kick off the gui--the shellgui module is class library only example - pp \gui\shellgui\mytools py #!/usr/local/bin/python ""###############################################################################provide type-specific option sets for application ###############################################################################""from shellgui import from packdlg import runpackdialog from unpkdlg import rununpackdialog type-specific option gui dialogs for data entry they both run app classes class textpak (listmenugui)def __init__(self)self mymenu [('pack 'runpackdialog)('unpack'rununpackdialog)('mtool 'self notdone)listmenugui __init__(selfdef fortoolbar(selflabel)return label in {'pack ''unpack'simple functions use same width here method from guimixin set syntax shellguiguis for command-line tools
5,186
def __init__(self)self mymenu {'pack 'runpackdialog'unpack'rununpackdialog'mtool 'self notdonedictmenugui __init__(selfif __name__ ='__main__'from sys import argv if len(argv and argv[ ='list'print('list test'textpak (mainloop(elseprint('dict test'textpak (mainloop(or use input here instead of in dialogs self-test code 'menugui py list|^the classes in this module are specific to particular tool setto display different set of tool namessimply code and run new subclass by separating out application logic into distinct subclasses and modules like thissoftware can become widely reusable figure - shows the main shellgui window created when the mytools script is run with its list-based menu layout class on windows along with menu tear-offs so that you can see what they contain this window' menu and toolbar are built by gui makerand its quit and help buttons and menu selections trigger quit and help methods inherited from guimixin through the shellgui module' superclasses are you starting to see why this book preaches code reuse so oftenfigure - mytools items in shellgui window gui coding techniques
5,187
so farwe've coded general shell tools class libraryas well as an application-specific tool set module that names callback handlers in its option menus to complete the picturewe still need to define the callback handlers run by the guias well as the scripts they ultimately invoke non-gui scripts to test the shell gui' ability to run command-line scriptswe need few commandline scriptsof course at the bottom of the hierarchythe following two scripts make use of system tools and techniques from part ii to implement simple text file archive utility the firstexample - simply concatenates the contents of multiple text files into single filewith predefined separator lines between them example - pp \gui\shellgui\packer py pack text files into single file with separator lines (simple archiveimport sysglob marker ': 'textpak=>hopefully unique separator def pack(ofileifiles)output open(ofile' 'for name in ifilesprint('packing:'nameinput open(name' 'read(if input[- !'\ 'input +'\noutput write(marker name '\ 'output write(inputopen the next input file make sure it has endline write separator line and write the file' contents if __name__ ='__main__'ifiles [for patt in sys argv[ :]ifiles +glob glob(pattpack(sys argv[ ]ifilesnot globbed auto on windows pack files listed on cmdline the second scriptexample - scans archive files created by the firstto unpack into individual files again example - pp \gui\shellgui\unpacker py unpack files created by packer py (simple textfile archiveimport sys from packer import marker mlen len(markerdef unpack(ifileprefix='new-')for line in open(ifile)if line[:mlen!markeroutput write(lineuse common separator key filenames after markers for all input lines write real lines shellguiguis for command-line tools
5,188
name prefix line[mlen:- print('creating:'nameoutput open(name' 'or make new output if __name__ ='__main__'unpack(sys argv[ ]these scripts are fairly basicand this gui part of the book assumes you've already scanned the system tools so we won' go into their code in depth variants of these scripts appeared in the first edition of this book in actually used them early on in my python career to bundle files before could rely on tools like tar and zip to be present on all the machines used (and before python grew tar and zip support modules in its standard librarytheir operation is straightforward--consider these three text filesc:\pp \gui\shellguitype spam txt spam spam spam :\pp \gui\shellguitype eggs txt eggs :\pp \gui\shellguitype ham txt when run from the command linethe packer script combines them into single text fileand the unpacker extracts them from therethe packer must take care to glob (expandfilename patternsbecause this isn' done by default in windowsc:\pp \gui\shellguipacker py packed txt txt packingeggs txt packingham txt packingspam txt :\pp \gui\shellguiunpacker py packed txt creatingnew-eggs txt creatingnew-ham txt creatingnew-spam txt the result files have unique name by default (with an added prefix to avoid accidental overwritesespecially during testing)but you otherwise get back what you packedc:\pp \gui\shellguitype new-spam txt spam spam spam :\pp \gui\shellguitype packed txt ::::::::::::::::::::textpak=>eggs txt eggs ::::::::::::::::::::textpak=>ham txt gui coding techniques
5,189
::::::::::::::::::::textpak=>spam txt spam spam spam these scripts don' do anything about binary filescompressionor the likebut they serve to illustrate command-line scripts that require arguments when run although they can be launched with shell commands as above (and hence python tools like os popen and subprocess)their logic is also packaged to be imported and called for running them from guiwe'll use the latter direct call interface gui input dialogs one final piece remains as isthe packing and unpacking scripts function well as command-line tools the callback actions named in example - ' mytools py guithoughare expected to do something gui-oriented because the original file packing and unpacking scripts live in the world of text-based streams and shellswe need to code wrappers that accept input parameters from more gui-minded users in particularwe need dialogs that prompt for the command-line arguments required firstthe module in example - and its client script in example - use the custom modal dialog techniques we studied in to pop up an input display to collect pack script parameters the code in example - was split off to separate module because it' generally usefulin factwe will reuse itin both the unpack dialog and again in pyedit in this is yet another way to automate gui construction--using it to build form' rows trades or more lines of code per row ( without linked variable or browse buttonfor just we'll see another even more automatic form building approach in ' form py the utility herethoughis sufficient to shave dozens of lines of code for nontrivial forms example - pp \gui\shellgui\formrows py """create label+entry row framewith optional file open browse buttonthis is separate module because it can save code in other programs toocaller (or callbacks here)retain returned linked var while row is in use""from tkinter import from tkinter filedialog import askopenfilename widgets and presets file selector dialog def makeformrow(parentlabelwidth= browse=trueextend=false)var stringvar(row frame(parentlab label(rowtext=label '?'relief=ridgewidth=widthent entry(rowrelief=sunkentextvariable=varshellguiguis for command-line tools
5,190
uses packed row frames lab pack(side=leftand fixed-width labels ent pack(side=leftexpand=yesfill=xor use grid(rowcolif browsebtn button(rowtext='browse 'btn pack(side=rightif not extendbtn config(commandlambdavar set(askopenfilename(or var get()elsebtn config(commandlambdavar set(var get(askopenfilename()return var nextexample - ' runpackdialog function is the actual callback handler invoked when tool names are selected in the main shellgui window it uses the form row builder module of example - and applies the custom modal dialog techniques we studied earlier example - pp \gui\shellgui\packdlg py popup gui dialog for packer script argumentsand run it from glob import glob from tkinter import from packer import pack from formrows import makeformrow filename expansion gui widget stuff use pack script/module use form builder tool def packdialog() new top-level window win toplevel(with row frames ok button win title('enter pack parameters'var makeformrow(winlabel='output file'var makeformrow(winlabel='files to pack'extend=truebutton(wintext='ok'command=win destroypack(win grab_set(win focus_set(go modalmouse grabkeyboard focuswait win wait_window(wait till destroyelse returns now return var get()var get(fetch linked var values def runpackdialog()outputpatterns packdialog(if output !"and patterns !""patterns patterns split(filenames [for sublist in map(globpatterns)filenames +sublist print('packer:'outputfilenamespack(ofile=outputifiles=filenamespop-up gui dialog till ok or wm-destroy do non-gui part now do expansion manually unix shells do this auto should show msgs in gui too if __name__ ='__main__'root tk(button(roottext='popup'command=runpackdialogpack(fill=xbutton(roottext='bye'command=root quitpack(fill=xroot mainloop( gui coding techniques
5,191
form shown in figure - this is also what we get when its main function is launched by the mytools py shell tools gui users may either type input and output filenames into the entry fields or press the "browsebuttons to pop up standard file selection dialogs they can also enter filename patterns--the manual glob call in this script expands filename patterns to match names and filters out nonexistent input filenames againthe unix command line does this pattern expansion automatically when running the packer from shellbut windows does not figure - the packdlg input form when the form is filled in and submitted with its ok buttonparameters are finally passed along to the main function of the non-gui packer script listed earlier to perform file concatenations the gui interface to the unpacking script is simpler because there is only one input field--the name of the packed file to scan we also get to reuse the form row builder module developed for the packer' dialogbecause this task is so similar the script in example - (and its main function run by the mytools py shell tool gui' selectionsgenerates the input form window shown in figure - figure - the unpkdlg input form example - pp \gui\shellgui\unpkdlg py popup gui dialog for unpacker script argumentsand run it from tkinter import from unpacker import unpack from formrows import makeformrow widget classes use unpack script/module form fields builder def unpackdialog()shellguiguis for command-line tools
5,192
win title('enter unpack parameters'var makeformrow(winlabel='input file'width= win bind(''lambda eventwin destroy()win grab_set(win focus_set(make myself modal win wait_window(till ' destroyed on return return var get(or closed by wm action def rununpackdialog()input unpackdialog(if input !''print('unpacker:'inputunpack(ifile=inputprefix=''get input from gui do non-gui file stuff run with input from dialog if __name__ ="__main__"button(nonetext='popup'command=rununpackdialogpack(mainloop(the "browsebutton in figure - pops up file selection dialog just as the packdlg form did instead of an ok buttonthis dialog binds the enter key-press event to kill the window and end the modal wait state pauseon submissionthe name of the packed file is passed to the main function of the unpacker script shown earlier to perform the actual file scan process room for improvement all of this works as advertised--by making command-line tools available in graphical form like thisthey become much more attractive to users accustomed to the gui way of life we've effectively added simple gui front-end to command-line tools stilltwo aspects of this design seem prime for improvement firstboth of the input dialogs use common code to build the rows of their input formsbut it' tailored to this specific use casewe might be able to simplify the dialogs further by importing more generic form-builder module instead we met general form builder code in and and we'll meet more later--see the form py module in for pointers on further genericizing form construction secondat the point where the user submits input data in either form dialogwe've lost the gui trail--the gui is blockedand messages are routed back to the console the gui is technically blocked and will not update itself while the pack and unpack utilities runalthough these operations are fast enough for my files as to be negligiblewe would probably want to spawn these calls off in threads for very large files to keep the main gui thread active (more on threads later in this the console issue is more blatantpacker and unpacker messages still show up in the stdout console windownot in the gui (all the filenames here include full directory paths if you select them with the gui' browse buttonscourtesy of the standard open dialog) gui coding techniques
5,193
pp scrolledtext list test packerpacked all ['spam txt''ham txt''eggs txt'packingspam txt packingham txt packingeggs txt unpackerpacked all creatingspam txt creatingham txt creatingeggs txt this may be less than ideal for gui' usersthey may not expect (or even be able to findthe command-line console we can do better hereby redirecting stdout to an object that throws text up in gui window as it is received you'll have to read the next section to see how guistreamsredirecting streams to widgets on to our next gui coding techniquein response to the challenge posed at the end of the last sectionthe script in example - arranges to map input and output sources to pop-up windows in gui applicationmuch as we did with strings in the stream redirection topics in although this module is really just first-cut prototype and needs improvement itself ( each input line request pops up new input dialog--not exactly award winning ergonomics!)it demonstrates the concepts in general example - ' guioutput and guiinput objects define methods that allow them to masquerade as files in any interface that expects real file as we learned earlier in this includes both the print and input built-in functions for accessing standard streamsas well as explicit calls to the read and write methods of file objects the two top-level interfaces in this module handle common use casesthe redirectedguifunc function uses this plug-and-play file compatibility to run function with its standard input and output streams mapped completely to popup windows rather than to the console window (or wherever streams would otherwise be mapped in the system shellthe redirectedguishellcmd function similarly routes the output of spawned shell command line to pop-up window it can be used to display the output of any program in gui--including that printed by python program the module' guiinput and guioutput classes can also be used or customized directly by clients that need to match more direct file method interface or need more finegrained control over the process guistreamsredirecting streams to widgets
5,194
""##############################################################################first-cut implementation of file-like classes that can be used to redirect input and output streams to gui displaysas isinput comes from common dialog pop-up ( single output+input interface or persistent entry field for input would be better)this also does not properly span lines for read requests with byte count len(line)could also add __iter__/__next__ to guiinput to support line iteration like files but would be too many popups##############################################################################""from tkinter import from tkinter simpledialog import askstring from tkinter scrolledtext import scrolledtext class guioutputfont ('courier' 'normal'def __init__(selfparent=none)self text none if parentself popupnow(parentor pp gui tour scrolledtext in class for allself for one pop up now or on first write def popupnow(selfparent=none)in parent nowtoplevel later if self textreturn self text scrolledtext(parent or toplevel()self text config(font=self fontself text pack(def write(selftext)self popupnow(self text insert(endstr(text)self text see(endself text update(update gui after each line def writelines(selflines)for line in linesself write(linelines already have '\nor map(self writelinesclass guiinputdef __init__(self)self buff 'def inputline(self)line askstring('guiinput''enter input line (cancel=eof)'if line =nonereturn 'pop-up dialog for each line elsecancel button means eof return line '\nelse add end-line marker def read(selfbytes=none)if not self buffself buff self inputline(if bytestext self buff[:bytesself buff self buff[bytes:else gui coding techniques read by byte count doesn' span lines
5,195
line self buff while linetext text line line self inputline(return text def readline(self)text self buff or self inputline(self buff 'return text def readlines(self)lines [while truenext self readline(if not nextbreak lines append(nextreturn lines def redirectedguifunc(func*pargs**kargs)import sys savestreams sys stdinsys stdout sys stdin guiinput(sys stdout guioutput(sys stderr sys stdout result func(*pargs**kargssys stdinsys stdout savestreams return result def redirectedguishellcmd(command)import os input os popen(command' 'output guioutput(def reader(inputoutput)while trueline input readline(if not linebreak output write(linereader(inputoutputread all till eof until cancel=eof='emulate file read methods read all lines map func streams to pop ups pops up dialog as needed new output window per call this is blocking call show shell command' standard output in new pop-up text box widgetthe readline call may block if __name__ ='__main__'def makeupper()while truetryline input('line'exceptbreak print(line upper()print('end of file'self test when run use standard streams def makelower(inputoutput)while trueline input readline(if not linebreak use explicit files guistreamsredirecting streams to widgets
5,196
print('end of file'root tk(button(roottext='test streams'command=lambdaredirectedguifunc(makeupper)pack(fill=xbutton(roottext='test files 'command=lambdamakelower(guiinput()guioutput()pack(fill=xbutton(roottext='test popen 'command=lambdaredirectedguishellcmd('dir *')pack(fill=xroot mainloop(as coded hereguioutput attaches scrolledtext (python' standard library flavorto either passed-in parent container or new top-level window popped up to serve as the container on the first write call guiinput pops up new standard input dialog every time read request requires new line of input neither one of these policies is ideal for all scenarios (input would be better mapped to more long-lived widget)but they prove the general point intended figure - shows the scene generated by this script' self-test codeafter capturing the output of windows shell dir listing command (on the leftand two interactive loop tests (the one with "line?prompts and uppercase letters represents the makeupper streams redirection testan input dialog has just popped up for new makelower files interface test figure - guistreams routing streams to pop-up windows this scene may not be spectacular to look atbut it reflects file and stream input and output operations being automatically mapped to gui devices--as we'll see in momentthis accomplishes most of the solution to the prior section' closing challenge before we move onwe should note that this module' calls to redirected function as well as its loop that reads from spawned shell command are potentially blocking- gui coding techniques
5,197
although guioutput takes care to call tkinter' update method to update the display after each line is writtenthis module has no control in general over the duration of functions or shell commands it runs in redirectedguishellcmdfor examplethe call to input readline will pause until an output line is received from the spawned programrendering the gui unresponsive because the output object runs an update callthe display is still updated during the program' execution (an update call enters the tk event loop momentarily)but only as often as lines are received from the spawned program in additionbecause of this function' loopthe gui is committed to the shell command in general until it exits calls to redirected function in redirectedguifunc are similarly blocking in generalmoreoverduring the call' duration the display is updated only as often as the function issues output requests in other wordsthis blocking model is simplistic and might be an issue in larger gui we'll revisit this later in the when we meet threads for nowthe code suits our present purpose using redirection for the packing scripts nowfinallyto use such redirection tools to map command-line script output back to guiwe simply run calls and command lines with the two redirected functions in this module example - shows one way to wrap the packing operation dialog of the shell gui section' example - to force its printed output to appear in popup window when generatedinstead of in the console example - pp \gui\shellgui\packdlg-redirect py wrap command-line script in gui redirection tool to pop up its output from tkinter import from packdlg import runpackdialog from pp gui tools guistreams import redirectedguifunc def runpackdialog_wrapped()redirectedguifunc(runpackdialogcallback to run in mytools py wrap entire callback handler if __name__ ='__main__'root tk(button(roottext='pop'command=runpackdialog_wrappedpack(fill=xroot mainloop(you can run this script directly to test its effectwithout bringing up the shellgui window figure - shows the resulting stdout window after the pack input dialog is dismissed this window pops up as soon as script output is generatedand it is bit more gui user friendly than hunting for messages in console you can similarly code the unpack parameters dialog to route its output to pop-up simply change guistreamsredirecting streams to widgets
5,198
mytools py in example - to register code like the function wrapper here as its callback handlers in factyou can use this technique to route the output of any function call or command line to pop-up windowas usualthe notion of compatible object interfaces is at the heart of much of python code' flexibility reloading callback handlers dynamically our next gui programming technique is all about changing gui while it is running-the ultimate in customization the python imp reload function lets you dynamically change and reload program' modules without stopping the program for instanceyou can bring up text editor window to change the source code of selected parts of system while it is running and see those changes show up immediately after reloading the changed module this is powerful featureespecially for developing programs that take long time to restart programs that connect to databases or network serversinitialize large objectsimplement long-running servicesor travel through long series of steps to retrigger callback are prime candidates for reload it can shave substantial time from the development cycle and make systems more flexible the catch for guisthoughis that because callback handlers are registered as object references rather than module and object namesreloads of callback handler functions are ineffective after the callback has been registered the python imp reload operation works by changing module object' contents in place because tkinter stores pointer to the registered handler object directlythoughit is oblivious to any reloads of the module that the handler came from that istkinter will still reference module' old objects even after the module is reloaded and changed this is subtle thingbut you really only need to remember that you must do something special to reload callback handler functions dynamically not only do you need to gui coding techniques
5,199
provide an indirection layer that routes callbacks from registered objects to modules so that reloads have impact for examplethe script in example - goes the extra mile to indirectly dispatch callbacks to functions in an explicitly reloaded module the callback handlers registered with tkinter are method objects that do nothing but reload and dispatch again because the true callback handler functions are fetched through module objectreloading that module makes the latest versions of the functions accessible example - pp \gui\tools\rad py reload callback handlers dynamically from tkinter import import radactions from imp import reload get initial callback handlers moved to module in python class hello(frame)def __init__(selfmaster=none)frame __init__(selfmasterself pack(self make_widgets(def make_widgets(self)button(selftext='message 'command=self message pack(side=leftbutton(selftext='message 'command=self message pack(side=rightdef message (self)reload(radactionsradactions message (need to reload actions module before calling now new version triggered by pressing button def message (self)reload(radactionsradactions message (selfchanges to radactions py picked up by reload call the most recent versionpass self def method (self)print('exposed method 'called from radactions function hello(mainloop(when runthis script makes two-button window that triggers the message and message methods example - contains the actual callback handler code its functions receive self argument that gives access back to the hello class objectas though these were real methods you can change this file any number of times while the rad script' gui is activeeach time you do soyou'll change the behavior of the gui when button press occurs example - pp \gui\tools\radactions py callback handlersreloaded each time triggered def message ()change me reloading callback handlers dynamically