id
int64
0
25.6k
text
stringlengths
0
4.59k
5,200
def message (self)print('nini!'self method (or could build dialog change me access the 'helloinstance try running rad and editing the messages printed by radactions in another windowyou should see your new messages printed in the stdout console window each time the gui' buttons are pressed this example is deliberately simple to illustrate the conceptbut the actions reloaded like this in practice might build pop-up dialogsnew top-level windowsand so on reloading the code that creates such windows would also let us dynamically change their appearances there are other ways to change gui while it' running for instancewe saw in that appearances can be altered at any time by calling the widget config methodand widgets can be added and deleted from display dynamically with methods such as pack_forget and pack (and their grid manager relativesfurthermorepassing new command=action option setting to widget' config method might reset callback handler to new action object on the flywith enough support codethis may be viable alternative to the indirection scheme used earlier to make reloads more effective in guis of coursenot all guis need to be so dynamic imagine game which allows character modificationthough--dynamic reloads in such system can greatly enhance their utility ( 'll leave the task of extending this example with massively multiplayer online role-playing game server as suggested exercise wrapping up top-level window interfaces top-level window interfaces were introduced in this section picks up where that introduction left off and wraps up those interfaces in classes that automate much of the work of building top-level windows--setting titlesfinding and displaying window iconsissuing proper close actions based on window' roleintercepting window manager close button clicksand so on example - provides wrapper classes for the most common window types-- main application windowa transient pop-up windowand an embedded gui component window these window types vary slightly in terms of their close operationsbut most inherit common functionality related to window bordersiconstitlesand close buttons by creatingmixing inor subclassing the class for the type of window you wish to makeyou'll get all its setup logic for free example - pp \gui\tools\windows py ""##############################################################################classes that encapsulate top-level interfaces allows same gui to be mainpop-upor attachedcontent classes may inherit gui coding techniques
5,201
be called directly without subclassdesigned to be mixed in after (further to the right thanapp-specific classeselsesubclass gets methods here (destroyokaytoquit)instead of from app-specific classes--can' redefine ##############################################################################""import osglob from tkinter import tktoplevelframeyesbothridge from tkinter messagebox import showinfoaskyesno class _window""mixin shared by main and pop-up windows ""foundicon none iconpatt 'icoiconmine 'py icoshared by all inst may be reset def configborders(selfappkindiconfile)if not iconfileiconfile self findicon(title app if kindtitle +kind self title(titleself iconname(appif iconfiletryself iconbitmap(iconfileexceptpass self protocol('wm_delete_window'self quitno icon passedtry curr,tool dirs on window border when minimized window icon image bad py or platform don' close silent def findicon(self)if _window foundiconreturn _window foundicon iconfile none iconshere glob glob(self iconpattif iconshereiconfile iconshere[ elsemymod __import__(__name__path __name__ split('for mod in path[ :]mymod getattr(mymodmodmydir os path dirname(mymod __file__myicon os path join(mydirself iconmineif os path exists(myicon)iconfile myicon _window foundicon iconfile return iconfile already found onetry curr dir first assume just one del icon for red tk try tools dir icon import self for dir poss package path follow path to end only have leftmost use myiconnot tk don' search again class mainwindow(tk_window)""when run in main top-level window ""wrapping up top-level window interfaces
5,202
tk __init__(selfself __app app self configborders(appkindiconfiledef quit(self)if self okaytoquit()threads runningif askyesno(self __app'verify quit program?')self destroy(quit whole app elseshowinfo(self __app'quit not allowed'or in okaytoquitdef destroy(self)tk quit(selfexit app silently redef if exit ops def okaytoquit(self)return true redef me if used thread busy class popupwindow(toplevel_window)""when run in secondary pop-up window ""def __init__(selfappkind=''iconfile=none)toplevel __init__(selfself __app app self configborders(appkindiconfiledef quit(self)if askyesno(self __app'verify quit window?')self destroy(redef me to change or call destroy quit this window def destroy(self)toplevel destroy(selfclose win silently redef for close ops class quietpopupwindow(popupwindow)def quit(self)self destroy(don' verify close class componentwindow(frame)""when attached to another display ""def __init__(selfparent)frame __init__(selfparentself pack(expand=yesfill=bothself config(relief=ridgeborder= if not frame provide container reconfig to change def quit(self)showinfo('quit''not supported in attachment mode'destroy from frameerase frame silent redef for close ops so why not just set an application' icon and title by calling protocol methods directlyfor one thingthose are the sorts of details that are easy to forget (you will probably wind up cutting and pasting code much of the timefor anotherthese classes add gui coding techniques
5,203
other thingsthe classes arrange for automatic quit verification dialog pop ups and icon file searching for instancethe window classes always search the current working directory and the directory containing this module for window icon fileonce per process by using classes that encapsulate--that ishide--such detailswe inherit powerful tools without having to think about their implementation again in the future moreoverby using such classeswe'll give our applications standard look-and-feel and behavior and if we ever need to change that appearance or behaviorwe have to change code in only one placenot in every window we implement to test this utility moduleexample - exercises its classes in variety of modes-as mix-in classesas superclassesand as calls from nonclass code example - pp \gui\tools\windows-test py must import windows to testelse __name__ is __main__ in findicon from tkinter import buttonmainloop from windows import mainwindowpopupwindowcomponentwindow def _selftest()mixin usage class content"same code used as tktopleveland framedef __init__(self)button(selftext='larch'command=self quitpack(button(selftext='sing 'command=self destroypack(class contentmix(mainwindowcontent)def __init__(self)mainwindow __init__(self'mixin''main'content __init__(selfcontentmix(class contentmix(popupwindowcontent)def __init__(self)popupwindow __init__(self'mixin''popup'content __init__(selfprev contentmix(class contentmix(componentwindowcontent)def __init__(self)componentwindow __init__(selfprevcontent __init__(selfcontentmix(nested frame on prior window sing erases frame subclass usage class contentsub(popupwindow)def __init__(self)popupwindow __init__(self'popup''subclass'wrapping up top-level window interfaces
5,204
button(selftext='sing'command=self destroypack(contentsub(non-class usage win popupwindow('popup''attachment'button(wintext='redwood'command=win quitpack(button(wintext='sing 'command=win destroypack(mainloop(if __name__ ='__main__'_selftest(when runthe test generates the window in figure - all generated windows get blue "pyicon automaticallyand intercept and verify the window manager' upper right corner "xclose buttonthanks to the search and configuration logic they inherit from the window module' classes some of the buttons on the test windows close just the enclosing windowsome close the entire applicationsome erase an attached windowand others pop up quit verification dialog run this on your own to see what the examplesbuttons doso you can correlate with the test codequit actions are tailored to make sense for the type of window being run figure - windows-test display we'll use these window protocol wrappers in the next pyclock exampleand then again later in where they'll come in handy to reduce the complexity of the pymailgui program part of the benefit of doing oop in python now is that we can forget the details later gui coding techniques
5,205
in we learned about threads and the queue mechanism that threads typically use to communicate with one another we also described the application of those ideas to guis in the abstract in we specialized some of these topics to the tkinter gui toolkit we're using in this book and expanded on the threaded gui model in generalincluding thread safety (or lack thereofand the roles of queues and locks now that we've become fully functional gui programmerswe can finally see what these ideas translate to in terms of code if you skipped the related material in or you should probably go back and take look firstwe won' be repeating the thread or queue background material in its entirety here the application to guishoweveris straightforward recall that long-running operations must generally be run in parallel threadsto avoid blocking the gui from updating itself or responding to new user requests long-running operations can include time-intensive function callsdownloads from serversblocking input/output callsand any task which might insert noticeable delay in our packing and unpacking examples earlier in this for instancewe noted that the calls to run the actual file processing should generally run in threads so that the main gui thread is not blocked until they finish in the general caseif gui waits for anything to finishit will be completely unresponsive during the wait--it can' be resizedit can' be minimizedand it won' even redraw itself if it is covered and uncovered by other windows to avoid being blocked this waythe gui must run long-running tasks in parallelusually with threads that can share program state that waythe main gui thread is freed up to update the display and respond to new user interactions while threads do other work as we've also seenthe tkinter update call can help in some contextsbut it only refreshes the display when it can be calledthreads fully parallelize long-running operations and offer more general solution howeverbecauseas we learned in only the main thread should generally update gui' displaythreads you start to handle long-running tasks should not update the display with results themselves ratherthey should place data on queue (or other mechanism)to be picked up and displayed by the main gui thread to make this workthe main thread typically runs timer-based loop that periodically checks the queue for new results to be displayed spawned threads produce and queue data but know nothing about the guithe main gui thread consumes and displays results but does not generate them because of its division of laborwe usually call this producer/consumer model--task threads produce data which the gui thread consumes the long-running task threads are also sometimes called workersbecause they handle the work of producing results behind the scenesfor the gui to present to user in some sensethe gui is also client to worker thread serversthough that terminology is usually reserved for more guisthreadsand queues
5,206
more loosely coupled (though gui can also display data from independent serverswhatever we call itthis model both avoids blocking the gui while tasks run and avoids potentially parallel updates to the gui itself as more concrete examplesuppose your gui needs to display telemetry data sent in real time from satellite over sockets (an ipc tool introduced in your program has to be responsive enough to not lose incoming databut it also cannot get stuck waiting for or processing that data to achieve both goalsspawn threads that fetch the incoming data and throw it on queueto be picked up and displayed periodically by the main gui thread with such separation of laborthe gui isn' blocked by the satellitenor vice versa--the gui itself will run independently of the data streamsbut because the data stream threads can run at full speedthey'll be able to pick up incoming data as fast as it' sent gui event loops are not generally responsive enough to handle real-time inputs without the data stream threadswe might lose incoming telemetrywith themwe'll receive data as it is sent and display it as soon as the gui' event loop gets around to picking it up off the queue--plenty fast for the real human user to see if no data is sentonly the spawned threads waitnot the gui itself in other scenariosthreads are required just so that the gui remains active during longrunning tasks while downloading reply from web serverfor exampleyour gui must be able to redraw itself if covered or resized because of thatthe download call cannot be simple function callit must run in parallel with the rest of your program-typicallyas thread when the result is fetchedthe thread must notify the gui that data is ready to be displayedby placing the result on queuethe notification is simple--the main gui thread will find it the next time it checks the queue in its timer callback function for examplewe'll use threads and queues this way in the pymailgui program in to allow multiple overlapping mail transfers to occur without blocking the gui itself placing data on queues whether your guis interface with satelliteswebsitesor something elsethis threadbased model turns out to be fairly simple in terms of code example - is the gui equivalent of the queue-based threaded program we met earlier in (compare this with example - in the context of guithe consumer thread becomes the gui itselfand producer threads add data to be displayed to the shared queue as it is produced the main gui thread uses the tkinter after method to check the queue for results instead of an explicit loop example - pp \gui\tools\queuetest-gui py gui that displays data produced and queued by worker threads import _threadqueuetime dataqueue queue queue(infinite size gui coding techniques
5,207
for in range( )time sleep( print('put'dataqueue put('[producer id=%dcount=% ](idi)def consumer(root)tryprint('get'data dataqueue get(block=falseexcept queue emptypass elseroot insert('end''consumer got =% \nstr(data)root see('end'root after( lambdaconsumer(root) times per sec def makethreads()for in range( )_thread start_new_thread(producer( ,)if __name__ ='__main__'main gui threadspawn batch of worker threads on each mouse click from tkinter scrolledtext import scrolledtext root scrolledtext(root pack(root bind(''lambda eventmakethreads()consumer(rootstart queue check loop in main thread root mainloop(pop-up windowenter tk event loop observe how we fetch one queued data item per timer event here this is on purposealthough we could loop through all the data items queued on each timer eventthis might block the gui indefinitely in pathological cases where many items are queued quickly (imagine fast telemetry interface suddenly queueing hundreds or thousands of results all at onceprocessing one item at time ensures that the gui will return to its event loop to update the display and process new user inputs without becoming blocked the downside of this approach is that it may take awhile to work through very many items placed on the queue hybrid schemessuch as dispatching at most queued items per timer event callbackmight be useful in some such scenarioswe'll see an example like this later in this section (example - when this script is runthe main gui thread displays the data it grabs off the queue in the scrolledtext window captured in figure - new batch of four producer threads is started each time you left-click in the windowand threads issue "getand "putmessages to the standard output stream (which isn' synchronized in this example--printed messages might overlap occasionally on some platformsincluding windowsthe producer threads issue sleep calls to simulate long-running tasks such as downloading mailfetching query resultor waiting for input to show up on socket (more on sockets later in this left-clicked multiple times to encourage thread overlap in figure - guisthreadsand queues
5,208
recoding with classes and bound methods example - takes the model one small step further and migrates it to class to allow for future customization and reuse its operationwindowand output are the same as the prior non-object-oriented versionbut the queue is checked more oftenand there are no standard output prints notice how we use bound methods for button callbacks and thread actions herebecause bound methods retain both instance and methodthe threaded action has access to state informationincluding the shared queue this allows us to move the queue and the window itself from the prior version' global variables to instance object state example - pp \gui\tools\queuetest-gui-class py gui that displays data produced and queued by worker threads (class-basedimport threadingqueuetime from tkinter scrolledtext import scrolledtext or pp gui tour scrolledtext class threadgui(scrolledtext)threadsperclick def __init__(selfparent=none)scrolledtext __init__(selfparentself pack(self dataqueue queue queue(self bind(''self makethreadsself consumer( gui coding techniques infinite size on left mouse click queue loop in main thread
5,209
for in range( )time sleep( self dataqueue put('[producer id=%dcount=% ](idi)def consumer(self)trydata self dataqueue get(block=falseexcept queue emptypass elseself insert('end''consumer got =% \nstr(data)self see('end'self after( self consumer times per sec def makethreads(selfevent)for in range(self threadsperclick)threading thread(target=self producerargs=( ,)start(if __name__ ='__main__'root threadgui(root mainloop(in main threadmake guirun timer loop pop-up windowenter tk event loop watch for this threadtimer loopand shared queue technique to resurface later in this as well as in ' more realistic pyedit program example in pyeditwe'll use it to run external file searches in threadsso they avoid blocking the gui and may overlap in time we'll also revisit the classic producer/consumer thread queue model in more realistic scenario later in this as way to avoid blocking gui that must read an input stream--the output of another program thread exits in guis example - also uses python' threading module instead of _thread this would normally mean thatunlike the prior versionthe program would not exit if any producer threads are still runningunless they are made daemons manually by setting their daemon flag to true remember that under threadingprograms exit when only daemonic threads remainthe producer threads here inherit false daemon value from the thread that creates themwhich prevents program exit while they run howeverin this example the spawned threads finish too quickly to noticeably defer program exit change this script' time sleep call to seconds to simulate longerlived worker threads and witness this effect in action--closing the window after leftclick erases the windowbut the program itself then does not exit for roughly seconds ( its shell window is pausedif you do the same to the prior _thread versionor set this version' threadsdaemon flags to truethe program exits immediately instead in more realistic guisyou'll want to analyze exit policies in the context of running threadsand code accordinglyboth nondaemonic threading threads and thread locks in general can be used to defer exits if needed converselya perpetually running guisthreadsand queues
5,210
for more on program exits and daemonic threads (and other scary topics!placing callbacks on queues in the prior section' examplesthe data placed on the queue is always string that' sufficient for simple applications where there is just one type of producer if you may have many different kinds of threads producing many different types of results running at oncethoughthis can become difficult to manage you'll probably have to insert and parse out some sort of type or action information in the string so that the gui knows how to process it imagine an email clientfor instancewhere multiple sends and receives may overlap in timeif all threads share the same single queuethe information they place on it must somehow designate the sort of event it represents-- downloaded mail to displaya progress indicator updatea successful send completionand so on this isn' entirely hypotheticalwe'll confront this exact issue in ' pymailgui luckilyqueues support much more than just strings--any type of python object can be placed on queue perhaps the most general of these is callable objectby placing function or other callable object on the queuea producer thread can tell the gui how to handle the message in very direct way the gui simply calls the objects it pulls off the queue since threads all run within the same process and memory spaceany type of callable object works on queue--simple functionslambdasand even bound methods that combine function with an implied subject object that gives access to state information and methods any updates performed by the callback object update state shared across the entire process because python makes it easy to handle functions and their argument lists in generic fashionthis turns out to be easier than it might sound example - for instanceshows one way to throw callbacks on queue that we'll be using in for pymailgui this module comes with handful of tools its threadcounter class can be used as shared counter and boolean flag (for exampleto manage operation overlapthe real meat herethoughis the queue interface functions--in shortthey allow clients to launch threads which queue their exit actionsto be dispatched in the main thread by timer loop in some ways this example is just variation on those of the prior section--we still run timer loop here to pull items off the queue in the main thread for both responsiveness and efficiencythis timer loop pulls at most items on each timer eventnot just one (which may take too long or incur overheads for short timer delay)and not all queued (which may block indefinitely when many items are produced quicklywe'll leverage this per-event batching feature to work through many progress updates in pymailgui without having to devote cpu resources to quick timer events that are normally unnecessary gui coding techniques
5,211
queueand the producer threads have been generalized to place success or failure callback on the queue in response to exits and exceptions moreoverthe actions that run in producer threads receive progress status function whichwhen calledsimply adds progress indicator callback to the queue to be dispatched by the main thread we can use thisfor exampleto show progress in the gui during network downloads example - pp \gui\tools\threadtools py ""################################################################################system-wide thread interface utilities for guis implements single thread callback queue and checker timer loop shared by all the windows in programworker threads queue their exit and progress actions to be run in the main threadthis doesn' block the gui it just spawns operations and manages and dispatches exits and progressworker threads can overlap freely with the main threadand with other workers using queue of callback functions and arguments is more useful than simple data queue if there can be many kinds of threads running at the same time each kind may have different implied exit actions because gui api is not completely thread-safeinstead of calling gui update callbacks directly after thread main actionplace them on shared queueto be run from timer loop in the main threadnot child threadthis also makes gui update points less random and unpredictablerequires threads to be split into main actionexit actionsand progress action assumes threaded action raises an exception on failureand has 'progresscallback argument if it supports progress updatesalso assumes callbacks are either short-lived or update as they runand that queue will contain callback functions (or other callablesfor use in gui app requires widget in order to schedule and catch 'afterevent loop callbacksto use this model in non-gui contextscould use simple thread timer instead ################################################################################""run even if no threads tryimport _thread as thread except importerrorimport _dummy_thread as thread in standard lib now raise importerror to run with gui blocking if threads not available same interfaceno threads shared cross-process queue named in shared global scopelives in shared object memory import queuesys threadqueue queue queue(maxsize= infinite size ################################################################################in main thread periodically check thread completions queuerun implied gui actions on queue in this main gui threadone consumer (gui)and multiple producers (loaddelsend) simple list may suffice toolist append and guisthreadsand queues
5,212
queued callbacks on each timer event may block gui indefinitelybut running only one can take long time or consume cpu for timer events ( progress)assumes callback is either short-lived or updates display as it runsafter callback runthe code here reschedules and returns to event loop and updatesbecause this perpetual loop runs in main threaddoes not stop program exit################################################################################def threadchecker(widgetdelaymsecs= perevent= )for in range(perevent)try(callbackargsthreadqueue get(block=falseexcept queue emptybreak elsecallback(*args /sec /timer pass to set speed run < callbacks anything readyrun callback here widget after(delaymsecsreset timer event lambdathreadchecker(widgetdelaymsecsperevent)back to event loop ################################################################################in new thread run actionmanage thread queue puts for exits and progressrun action with args nowlater run oncalls with contextcalls added to queue here are dispatched in main thread onlyto avoid parallel gui updatesallows action to be fully ignorant of use in thread hereavoids running callbacks in thread directlymay update gui in threadsince passed func in shared memory called in threadprogress callback just adds callback to queue with passed argsdon' update in-progress counters herenot finished till exit actions taken off queue and dispatched in main thread by threadchecker################################################################################def threaded(actionargscontextonexitonfailonprogress)tryif not onprogresswait for action in this thread action(*argsassume raises exception if fails elsedef progress(*any)threadqueue put((onprogressany context)action(progress=progress*argsexceptthreadqueue put((onfail(sys exc_info()context)elsethreadqueue put((onexitcontext)def startthread(actionargscontextonexitonfailonprogress=none)thread start_new_threadthreaded(actionargscontextonexitonfailonprogress)################################################################################ thread-safe counter or flaguseful to avoid operation overlap if threads update other shared state beyond that managed by the thread callback queue ################################################################################ gui coding techniques
5,213
def __init__(self)self count self mutex thread allocate_lock(def incr(self)self mutex acquire(self count + self mutex release(def decr(self)self mutex acquire(self count - self mutex release(def __len__(self)return self count or use threading semaphore or with self mutextrue/false if used as flag ################################################################################self-test codesplit thread action into mainexitsprogress ################################################################################if __name__ ='__main__'self-test code when run import time or pp gui tour scrolledtext from tkinter scrolledtext import scrolledtext def onevent( )myname 'thread-%si startthreadaction threadactionargs ( )context (myname,)onexit threadexitonfail threadfailonprogress threadprogressthread' main action def threadaction(idrepsprogress)for in range(reps)time sleep( if progressprogress(iif id = raise exception code that spawns thread what the thread does progress callbackqueued odd numberedfail thread exit/progress callbacksdispatched off queue in main thread def threadexit(myname)text insert('end''% \texit\nmynametext see('end'def threadfail(exc_infomyname)text insert('end''% \tfail\ % \ (mynameexc_info[ ])text see('end'def threadprogress(countmyname)text insert('end''% \tprog\ % \ (mynamecount)text see('end'text update(works hererun in main thread make enclosing gui and start timer loop in main thread guisthreadsand queues
5,214
text scrolledtext(text pack(threadchecker(textstart thread loop in main thread text bind('' need list for maprange ok lambda eventlist(map(oneventrange( ))text mainloop(pop-up windowenter tk event loop this module' comments describe its implementationand its self-test code demonstrates how this interface is used notice how thread' behavior is split into main actionexit actionsand optional progress action--the main action runs in the new threadbut the others are queued to be dispatched in the main thread that isto use this moduleyou will essentially break modal operation into thread and post-thread stepswith an optional progress call generallyonly the thread step should be long running when example - is run standaloneon each button click in scrolledtestit starts up six threadsall running the threadaction function as this threaded function runscalls to the passed-in progress function place callback on the queuewhich invokes threadprogress in the main thread when the threaded function exitsthe interface layer will place callback on the queue that will invoke either threadexit or thread fail in the main threaddepending upon whether the threaded function raised an exception because all the callbacks placed on the queue are pulled off and run in the main thread' timer loopthis guarantees that gui updates occur in the main thread only and won' overlap in parallel figure - shows part of the output generated after clicking the example' window its exitfailureand progress messages are produced by callbacks added to the queue by spawned threads and invoked from the timer loop running in the main thread study this code for more details and try to trace through the self-test code this is bit complexand you may have to make more than one pass over this code to make sense of its juggling act once you get the hang of this paradigmthoughit provides general scheme for handling heterogeneous overlapping threads in uniform way pymailguifor examplewill do very much the same as onevent in the self-test code herewhenever it needs to start mail transfer passing bound method callbacks on queues technicallyto make this even more flexiblepymailgui in will queue bound methods with this module--callable objects thatas mentionedpair method function with an instance that gives access to state information and other methods in this modethe thread manager module' client code takes form that looks more like example - revision of the prior example' self-test using classes and methods gui coding techniques
5,215
example - pp \gui\tools\threadtools-test-classes py tests thread callback queuebut uses class bound methods for action and callbacks import time from threadtools import threadcheckerstartthread from tkinter scrolledtext import scrolledtext class myguidef __init__(selfreps= )self reps reps uses default tk root self text scrolledtext(save widget as state self text pack(threadchecker(self textstart thread check loop self text bind('' need list for maprange ok lambda eventlist(map(self oneventrange( ))def onevent(selfi)myname 'thread-%si startthreadaction self threadactionargs ( )context (myname,)onexit self threadexitonfail self threadfailonprogress self threadprogressthread' main action def threadaction(selfidprogress)code that spawns thread what the thread does guisthreadsand queues
5,216
time sleep( if progressprogress(iif id = raise exception access to object state here progress callbackqueued odd numberedfail thread callbacksdispatched off queue in main thread def threadexit(selfmyname)self text insert('end''% \texit\nmynameself text see('end'def threadfail(selfexc_infomyname)have access to self state self text insert('end''% \tfail\ % \ (mynameexc_info[ ])self text see('end'def threadprogress(selfcountmyname)self text insert('end''% \tprog\ % \ (mynamecount)self text see('end'self text update(works hererun in main thread if __name__ ='__main__'mygui(text mainloop(this code both queues bound methods as thread exit and progress actions and runs bound methods as the thread' main action itself as we learned in because threads all run in the same process and memory spacebound methods reference the original in-process instance objectnot copy of it this allows them to update the gui and other implementation state directly furthermorebecause bound methods are normal objects which pass for callables interchangeably with simple functionsusing them both on queues and in threads this way just works to manythis broadly shared state of threads is one of their primary advantages over processes watch for the more realistic application of this module in ' pymailguiwhere it will serve as the core thread exit and progress dispatch engine therewe'll also run bound methods as thread actionstooallowing both threads and their queued actions to access shared mutable object state of the gui as we'll seequeued action updates are automatically made thread-safe by this module' protocolbecause they run in the main thread only other state updates to shared objects performed in spawned threadsthoughmay still have to be synchronized separately if they might overlap with other threadsand are made outside the scope of the callback queue direct update to mail cachefor instancemight lock out other operations until finished more ways to add guis to non-gui code sometimesguis pop up quite unexpectedly perhaps you haven' learned gui programming yetor perhaps you're just pining for non-event-driven days past but for whatever reasonyou may have written program to interact with user in an interactive consoleonly to decide later that interaction in real gui would be much nicer what to do gui coding techniques
5,217
restructure it to initialize widgets on startupcall mainloop once to start event processing and display the main windowand move all program logic into callback functions triggered by user actions your original program' actions become event handlersand your original main flow of control becomes program that builds main windowcalls the gui' event loop onceand waits this is the traditional way to structure gui programand it makes for coherent user experiencewindows pop up on requestinstead of showing up at seemingly random times until you're ready to bite the bullet and perform such structural conversionthoughthere are other possibilities for examplein the shellgui section earlier in this we saw how to add windows to file packing scripts to collect inputs (example - and beyond)laterwe also saw how to redirect such scriptsoutputs to guis with the guioutput class (example - this approach works if the non-gui operation we're wrapping up in gui is single operationfor more dynamic user interactionother techniques might be needed it' possiblefor instanceto launch gui windows from non-gui main programby calling the tkinter mainloop each time window must be displayed it' also possible to take more grandiose approach and add completely separate program for the gui portion of your application to wrap up our survey of gui programming techniqueslet' briefly explore each scheme popping up gui windows on demand if you just want to add simple gui user interaction to an existing non-gui script ( to select files to open or save)it is possible to do so by configuring widgets and calling mainloop from the non-gui main program when you need to interact with the user this essentially makes the program gui-capablebut without persistent main window the trick is that mainloop doesn' return until the gui main window is closed by the user (or quit method calls)so you cannot retrieve user inputs from the destroyed window' widgets after mainloop returns to work around thisall you have to do is be sure to save user inputs in python objectthe object lives on after the gui is destroyed example - shows one way to code this idea in python example - pp \gui\tools\mainloopdemo py ""demo running two distinct mainloop callseach returns after the main window is closedsave user results on python objectgui is goneguis normally configure widgets and then run just one mainloopand have all their logic in callbacksthis demo uses mainloop calls to implement two modal user interactions from non-gui main programit shows one way to add gui component to an existing non-gui scriptwithout restructuring code""from tkinter import from tkinter filedialog import askopenfilenameasksaveasfilename more ways to add guis to non-gui code
5,218
def __init__(self,parent=none)frame __init__(self,parentself pack(label(selftext ="basic demos"pack(button(selftext='open'command=self openfilepack(fill=bothbutton(selftext='save'command=self savefilepack(fill=bothself open_name self save_name "def openfile(self)save user results self open_name askopenfilename(use dialog options here def savefile(self)self save_name asksaveasfilename(initialdir=' :\\python 'if __name__ ="__main__"display window once print('popup 'mydialog demo(attaches frame to default tk(mydialog mainloop(displayreturns after windows closed print(mydialog open_namenames still on objectthough gui gone print(mydialog save_namenon gui section of the program uses mydialog here display window again print('popup 'mydialog demo(re-create widgets again mydialog mainloop(window pops up again print(mydialog open_namenew values on the object again print(mydialog save_namenon gui section of the program uses mydialog again print('ending 'this program twice builds and displays simple two-button main window that launches file selection dialogsshown in figure - its outputprinted as the gui windows are closedlooks like thisc:\pp \gui\toolsmainloopdemo py popup :/users/mark/stuff/books/ /pp /dev/examples/pp /gui/tools/widgets py :/python /python exe popup :/users/mark/stuff/books/ /pp /dev/examples/pp /gui/tools/guimixin py :/python /lib/tkinter/__init__ py ending notice how this program calls mainloop twiceto implement two modal user interactions from an otherwise non-gui script it' ok to call mainloop more than oncebut this script takes care to re-create the gui' widgets before each call because they are destroyed when the previous mainloop call exits (widgets are destroyed internally inside tkeven though the corresponding python widget object still existsagainthis can make for an odd user experience compared to traditional gui program structure-windows seem to pop up from nowhere--but it' quick way to put gui face on script without reworking its code gui coding techniques
5,219
note that this is different from using nested (recursivemainloop calls to implement modal dialogsas we did in in that modethe nested mainloop call returns when the dialog' quit method is calledbut we return to the enclosing mainloop layer and remain in the realm of event-driven programming example - instead runs mainloop two different timesstepping into and out of the event-driven model twice finallynote that this scheme works only if you don' have to run any non-gui code while the gui is openbecause your script' mainline code is inactive and blocked while mainloop runs you cannotfor exampleapply this technique to use utilities like those in the guistreams module we met earlier in this to route user interaction from non-gui code to gui windows the guiinput and guioutput classes in that example assume that there is mainloop call running somewhere (they're gui-basedafter allbut once you call mainloop to pop up these windowsyou can' return to your non-gui code to interact with the user or the gui until the gui is closed and the mainloop call returns the net effect is that these classes can be used only in the context of fully gui program but reallythis is an artificial way to use tkinter example - works only because the gui can interact with the user independentlywhile the mainloop call runsthe script is able to surrender control to the tkinter mainloop call and wait for results that scheme won' work if you must run any non-gui code while the gui is open because of such constraintsyou will generally need main-window-plus-callbacks model in most gui programs--callback code runs in response to user interaction while the gui remains open that wayyour code can run while gui windows are active for an examplesee earlier in this for the way the non-gui packer and unpacker scripts were run from gui so that their results appear in guitechnicallythese scripts are run in gui callback handler so that their output can be routed to widget adding gui as separate programsockets ( second lookas mentioned earlierit' also possible to spawn the gui part of your application as completely separate program this is more advanced techniquebut it can make integration simple for some applications because of the loose coupling it implies it canfor instancehelp with the guistreams issues of the prior sectionas long as inputs and outputs are communicated to the gui over inter-process communication (ipcmore ways to add guis to non-gui code
5,220
detect incoming output to be displayed the non-gui script would not be blocked by mainloop call for examplethe gui could be spawned by the non-gui script as separate programwhere user interaction results can be communicated from the spawned gui to the script using pipessocketsfilesor other ipc mechanisms we met in the advantage to this approach is that it provides separation of gui and non-gui code--the nongui script would have to be modified only to spawn and wait for user results to appear from the separate gui programbut could otherwise be used as is moreoverthe nongui script would not be blocked while an in-process mainloop call runs (only the gui process would run mainloop)and the gui program could persist after the point at which user inputs are required by the scriptleading to fewer pop-up windows in other scenariosthe gui may spawn the non-gui script insteadand listen for its feedback on an ipc device connected to the script' output stream in even more complex arrangementsthe gui and non-gui script may converse back and forth over bidirectional connections examples - - and - provide simple example of these techniques in actiona non-gui script sending output to gui they represent non-gui and gui programs that communicate over sockets--the ipc and networking device we met briefly in and will explore in depth in the next part of the book the important point to notice as we study these files is the way the programs are linkedwhen the non-gui script prints to its standard outputthe printed text is sent over socket connection to the gui program other than the import and call to the socket redirection codethe non-gui program knows nothing at all about guis or socketsand the gui program knows nothing about the program whose output it displays because this model does not require existing scripts to be entirely rewritten to support guiit is ideal for scripts that otherwise run on the world of shells and command lines in terms of codewe first need some ipc linkage in between the script and the gui example - encapsulates the client-side socket connection used by non-gui code for reuse as isit' partial work in progress (notice the ellipses operator in its last few functions--python' notion of "to be decided,and equivalent to pass in this contextbecause sockets are covered in full in we'll defer other stream redirection modes until thenwhen we'll also flesh out the rest of this module the version of this module here implements just the client-side connection of the standard output stream to socket--perfect for gui that wants to intercept non-gui script' printed text example - pp \gui\tools\socket_stream_redirect py ""[partialtools for connecting streams of non-gui programs to sockets that gui (or othercan use to interact with the non-gui programsee and pp \sockets\internet for more complete treatment "" gui coding techniques
5,221
from socket import port host 'localhostdef redirectout(port=porthost=host)""connect caller' standard output stream to socket for gui to listenstart caller after listener startedelse connect fails before accept ""sock socket(af_inetsock_streamsock connect((hostport)caller operates in client mode file sock makefile(' 'file interfacetextbufferred sys stdout file make prints go to sock send def redirectin(port=porthost=host)def redirectbothasclient(port=porthost=host)def redirectbothasserver(port=porthost=host)see see see nextexample - uses example - to redirect its prints to socket on which gui server program may listenthis requires just two lines of code at the top of the scriptand is done selectively based upon the value of command-line argument (without the argumentthe script runs in fully non-gui mode)example - pp \gui\tools\socket-nongui py non-gui sideconnect stream to socket and proceed normally import timesys if len(sys argv from socket_stream_redirect import redirectout(link to gui only if requested connect my sys stdout to socket gui must be started first as is non-gui code while trueprint(time asctime()sys stdout flush(time sleep( print data to stdoutsent to gui process via socket must flush to sendbufferedno unbuffered mode- irrelevant and finallythe gui part of this exchange is the program in example - this script implements gui to display the text printed by the non-gui programbut it knows nothing of that other program' logic for the displaythe gui program prints to the stream redirection object we met earlier in this (example - )because this program runs gui mainloop callthis all just works we're also running timer loop here to detect incoming data on the socket as it arrivesinstead of waiting for the non-gui program to run to completion because the socket is set to be nonblockinginput calls don' wait for data to appearand hencedo not block the gui more ways to add guis to non-gui code
5,222
gui server sideread and display non-gui script' output import sysos from socket import including socket error from tkinter import tk from pp launchmodes import portablelauncher from pp gui tools guistreams import guioutput myport sockobj socket(af_inetsock_streamsockobj bind((''myport)sockobj listen( gui is serverscript is client config server before client print('starting'portablelauncher('nongui''socket-nongui py -gui')(print('accepting'connaddr sockobj accept(conn setblocking(falseprint('accepted'def checkdata()trymessage conn recv( #output write(message '\ 'print(messagefile=outputexcept errorprint('no data'root after( checkdataroot tk(output guioutput(rootcheckdata(root mainloop(spawn non-gui script wait for client to connect use nonblocking socket (false= don' block for input could do sys stdout=output too if readyshow text in gui window raises socket error if not ready print to sys stdout check once per second socket text is displayed on this start example - ' file to launch this example when both the gui and the nongui processes are runningthe gui picks up new message over the socket roughly once every two seconds and displays it in the window shown in figure - the gui' timer loop checks for data once per secondbut the non-gui script sends message every two seconds only due to its time sleep calls the printed output in the terminal windows is as follows--"no datamessages and lines in the gui alternate each secondc:\pp \gui\toolssocket-gui py starting nongui accepting accepted no data no data no data no data more gui coding techniques
5,223
notice how we're displaying bytes strings in figure - --even though the non-gui script prints textthe gui script reads it with the raw socket interfaceand sockets deal in binary byte strings in python run this example by yourself for closer look in high-level termsthe gui script spawns the non-gui script and displays pop-up window that shows the text printed by the non-gui script (the date and timethe non-gui script can keep running linearprocedural code to produce databecause only the gui script' process runs an eventdriven mainloop call moreoverunlike our earlier stream redirection explorations which simply connected the script' streams to gui objects running in the same processthis decoupled twoprocess approach prevents the gui from being blocked while waiting for the script to produce outputthe gui process remains fully and independently activeand simply picks up new results as they appear (more on this in the next sectionthis model is similar in spirit to our earlier thread queue examplesbut the actors here are separate programs linked by socketnot in-process function calls although we aren' going to get into enough socket details in this to fully explain this script' codethere are few fine points worth underscoring herethis example should probably be augmented to detect and handle an end-of-file signal from the spawned programand then terminate its timer loop the non-gui script could also start the gui insteadbut in the socket worldthe server' end (the guimust be configured to accept connections before the client more ways to add guis to non-gui code
5,224
non-gui connects to it or the non-gui script will be denied connection and will fail because of the buffered text nature of the socket makefile objects used for streams herethe client program is required to flush its printed output with sys stdout flush to send data to the gui--without this callthe gui receives and displays nothing as we'll learn in this isn' required for command pipesbut it is when streams are reset to wrapped sockets as done here these wrappers don' support unbuffered modes in python xand there is no equivalent to the - flag in this context (more on - and command pipes in the next sectionstay tuned for much more on this example and topic in its socket clientserver model works well and is general approach to connecting gui and non-gui codebut there are other coding alternatives worth exploring in the next section before we move on adding gui as separate programcommand pipes the net effect of the two programs of the preceding section is similar to gui program reading the output of shell command over pipe file with os popen (or the subprocess popen interface upon which it is basedas we'll see laterthoughsockets also support independent serversand can link programs running on remote machines across network-- much larger idea we'll be exploring in perhaps subtler and more significant for our gui exploration here is the fact that without an after timer loop and nonblocking input sources of the sort used in the prior sectionthe gui may become stuck and unresponsive while waiting for data from the non-gui program and may not be able to handle more than one data stream for instanceconsider the guistreams call we wrote in example - to redirect the output of shell command spawned with os popen to gui window we could use this with simplistic code like that in example - to capture the output of spawned python program and display it in separately running gui program' window this is as concise as it is because it relies on the read/write loop and guioutput class in example - to both manage the gui and read the pipeit' essentially the same as one of the options in that example' self-test codebut we read the printed output of python program here example - pp \gui\tools\pipe-gui py gui reader sideroute spawned program standard output to gui window from pp gui tools guistreams import redirectedguishellcmd redirectedguishellcmd('python - pipe-nongui py' gui coding techniques uses guioutput -uunbuffered
5,225
standard streams to be unbufferedso we get printed text immediately as it is producedinstead of waiting for the spawned program to completely finish we talked about this option in when discussing deadlocks and pipes recall that print writes to sys stdoutwhich is normally buffered when connected to pipe this way if we don' use the - flag here and the spawned program doesn' manually call sys stdout flushwe won' see any output in the gui until the spawned program exits or until its buffers fill up if the spawned program is perpetual loop that does not exitwe may be waiting long time for output to appear on the pipeand hencein the gui this approach makes the non-gui code in example - much simplerit just writes to standard output as usualand it need not be concerned with creating socket interface compare this with its socket-based equivalent in example - --the loop is the samebut we don' need to connect to sockets first (the spawning parent reads the normal output stream)and don' need to manually flush output as it' produced (the - flag in the spawning parent prevents bufferingexample - pp \gui\tools\pipe-nongui py non-gui sideproceed normallyno need for special code import time while trueprint(time asctime()time sleep( non-gui code sends to gui process no need to flush here start the gui script in example - it launches the non-gui program automaticallyreads its output as it is createdand produces the window in figure - --it' similar to the socket-based example' result in figure - but displays the str text strings we get from reading pipesnot the byte strings of sockets this worksbut the gui is odd--we never call mainloop ourselvesand we get default empty top-level window in factit apparently works at all only because the tkinter update call issued within the redirect function enters the tk event loop momentarily to process pending events to do betterexample - creates an enclosing gui and kicks off an event loop manually by the time the shell command is spawnedwhen runit produces the same output window (figure - example - pp \gui\tools\pipe-gui py gui reader sidelike pipes-gui but make root window and mainloop explicit from tkinter import from pp gui tools guistreams import redirectedguishellcmd def launch()redirectedguishellcmd('python - pipe-nongui py'more ways to add guis to non-gui code
5,226
window tk(button(windowtext='go!'command=launchpack(window mainloop(the - unbuffered flag is crucial here again--without ityou won' see the text output window the gui will be blocked in the initial pipe input call indefinitely because the spawned program' standard output will be queued up in an in-memory buffer on the other handthis - unbuffered flag doesn' prevent blocking in the prior section' socket schemebecause that example resets streams to other objects after the spawned program startsmore on this in also remember that the buffering argument in os popen (and subprocess popencontrols buffering in the callernot in the spawned program- pertains to the latter the specter of blocking input calls either way we code themhoweverwhen the guis of example - and example - are run they become unresponsive for two seconds at time while they read data from the os popen pipe in factthey are just plain sluggish--window movesresizesredrawsraisesand so onare delayed for up to two secondsuntil the non-gui program sends data to the gui to make the pipe read call return perhaps worseif you press the "go!button twice in the second version of the guionly one window updates itself every two secondsbecause the gui is stuck in the second button press callback--it never exits the loop that reads from the pipe until the spawned non-gui gui coding techniques
5,227
in the terminal windowbecause of such constraintsto avoid blocked statesa separately running gui cannot generally read data directly if its appearance may be delayed for instancein the socketbased scripts of the prior section (example - )the after timer loop allows the gui to poll for data instead of waitingand display it as it arrives because it doesn' wait for the data to show upits gui remains active in between outputs of coursethe real issue here is that the read/write loop in the guistreams utility function used is too simplisticissuing read call within gui is generally prone to blocking there are variety of ways we might try to avoid this updating guis within threads and other nonsolutions one candidate fix is to try to run the redirection loop call in thread--for exampleby changing the launch function in example - as follows (this is from file pipe-gui thread py on the examples distribution)def launch()import _thread _thread start_new_thread(redirectedguishellcmd('python - pipe-nongui py',)but then we would be updating the gui from spawned threadwhichas we've learnedis generally bad idea parallel updates can wreak havoc in guis if factwith this change the gui fails spectacularly--it hangs immediately on the first "go!button press on my windows laptopbecomes unresponsiveand must be forcibly closed this happens before (or perhaps duringthe creation of the new popup scrolled-text window when this example was run on windows xp for the prior edition of this bookit also hung on the first "go!press occasionally and always hung eventually if you pressed the button enough timesthe process had to be forcibly killed direct gui updates in threads are not viable solution alternativelywe could try to use the python select select call (described in to implement polling for data on the input pipeunfortunatelyselect works only on sockets in windows today (it also works on pipes and other file descriptors in unixin other contextsa separately spawned gui might also use signals to inform the nongui program when points of interaction ariseand vice versa (the python signal module and os kill call were introduced in the downside with this approach is that it still requires changes to the non-gui program to handle the signals named pipes (the fifo files introduced in are sometimes an alternative to the socket calls of the original examples - through - but sockets work on standard windows pythonand fifos do not (os mkfifo is not available in windows in python though it is in cygwin pythoneven where they do workwe would still need an after timer loop in the gui to avoid blocking more ways to add guis to non-gui code
5,228
input shows up on the input pipedef callback(filemask)read from file here import _tkintertkinter _tkinter createfilehandler(filetkinter readablecallbackthe file handler creation call is also available within tkinter and as method of tk instance object unfortunately againas noted near the end of this call is not available on windows and is unix-only alternative avoiding blocking input calls with non-gui threads as far more general solution to the blocking input delays of the prior sectionthe gui process might instead spawn thread that reads the socket or pipe and places the data on queue in factthe thread techniques we met earlier in this could be used directly in such role this waythe gui is not blocked while the thread waits for data to show upand the thread does not attempt to update the gui itself moreovermore than one data stream or long-running activity can overlap in time example - shows how the main trick this script employs is to split up the input and output parts of the original redirectedguishellcmd of the guistreams module we met earlier in example - by so doingthe input portion can be spawned off in parallel thread and not block the gui the main gui thread uses an after timer loop as usualto watch for data to be added by the reader thread to shared queue because the main thread doesn' read program output itselfit does not get stuck in wait states example - pp \gui\tools\pipe_gui py ""read command pipe in thread and place output on queue checked in timer loopallows script to display program' output without being blocked between its outputsspawned programs need not connect or flushbut this approaches complexity of sockets ""import _thread as threadqueueos from tkinter import tk from pp gui tools guistreams import guioutput stdoutqueue queue queue(def producer(input)while trueline input readline(stdoutqueue put(lineif not linebreak def consumer(outputrootterm='')tryline stdoutqueue get(block=falseexcept queue empty gui coding techniques infinite size ok to blockchild thread empty at end-of-file main threadcheck queue times/secok if empty
5,229
elseif not linestop loop at end-of-file output write(termelse display next line return output write(lineroot after( lambdaconsumer(outputrootterm)def redirectedguishellcmd(commandroot)input os popen(command' 'output guioutput(rootthread start_new_thread(producer(input,)consumer(outputrootstart non-gui program start reader thread if __name__ ='__main__'win tk(redirectedguishellcmd('python - pipe-nongui py'winwin mainloop(as usualwe use queue here to avoid updating the gui except in the main thread note that we didn' need thread or queue in the prior section' socket examplejust because we're able to poll socket to see whether it has data without blockingan after timer loop was enough for shell-command pipethougha thread is an easy way to avoid blocking when runthis program' self-test code creates scrolledtext window that displays the current date and time sent from the pipes-nongui py script in example - in factits window is identical to that of the prior versions (see figure - the window is updated with new line every two seconds because that' how often the spawned pipes-nongui script prints message to stdout note how the producer thread calls readline(to load just one line at time we can' use input calls that consume the entire stream all at once ( read()readlines())because such calls would not return until the program exits and sends end-of-file the read(ncall would work to grab one piece of the output as wellbut we assume that the output stream is text here also notice that the - unbuffered stream flag is used here againto get output as it is producedwithout itoutput won' show up in the gui at all because it is buffered in the spawned program (try it yourselfsockets and pipescompare and contrast let' see how we've done this script is similar in spirit to what we did in example - because of the way its code is structuredthoughexample - has major advantagebecause input calls are spawned off in thread this timethe gui is completely responsive window movesresizesand so forthhappen immediately because the gui is not blocked while waiting for the next output from the non-gui program the combination of pipethreadand queue works wonders here--the gui need not wait for the spawned programand the spawned thread need not update the gui itself more ways to add guis to non-gui code
5,230
blocking makes this redirectedguishellcmd much more generally useful than the original pipe version we coded compared to the sockets of the prior sectionthoughthis solution is bit of mixed bagbecause this gui reads the spawned program' standard outputno changes are required in the non-gui program unlike the socket-based example in the prior sectionthe non-gui program here needs no knowledge of the gui that will display its results--it need not connect to socket and need not flush its input streamas required for the earlier socket-based option although it requires no changes to the programs whose output is displayedthe gui code' complexity begins to approach that of the socket-based alternativeespecially if you strip away the boilerplate code required for all socket programs it does not directly support running the gui and non-gui programs separatelyor on remote machines as we'll see in sockets allow data to be passed between programs running on the same machine or across networks sockets apply to more use cases than displaying program' output stream if the gui must do more than display another program' outputsockets become more general solution--as we'll also learn laterbecause sockets are bidirectional data streamsthey allow data to be passed back and forth between two programs in more arbitrary ways other uses for threaded pipe guis despite its tradeoffsthe thread/queue/pipe-based approach for guis has fairly wide applicability to illustratehere' another quick usage example the following runs simple script normally from shell/terminal windowit prints one successively longer output line every two secondsc:\pp \gui\toolstype spams py import time for in range( )time sleep( print to standard output print('spaminothing gui about thisehc:\pp \gui\toolspython spams py spam spamspamspam spamspamspamspamspam spamspamspamspamspamspamspam spamspamspamspamspamspamspamspamspam let' wrap this up in guiwith code typed at the interactive prompt for variety the following imports the new gui redirection function as library component and uses it to create window that displays the script' five linesappearing every two seconds just as in the terminal windowfollowed by final line containing reflecting the spawned program' exit the resulting output window is captured in figure - gui coding techniques
5,231
from tkinter import tk from pipe_gui import redirectedguishellcmd root tk(redirectedguishellcmd('python - spams py'rootfigure - command pipe gui displaying another program' output if the spawned program exitsexample - ' producer thread detects end-of-file on the pipe and puts final empty line in the queuein response the consumer loop displays an line in the gui by default when it detects this condition in this caseprogram exit is normal and silentin other caseswe may need to add shutdown logic to suppress error messages note that here againthe sleep call in the spawned program simulates long-running taskand we really need the - unbuffered streams flag--without itno output appears in the gui for eight secondsuntil the spawned program is completely finished with itthe gui receives and displays each line as it is printedone every two seconds this is alsofinallythe sort of code you could use to display the output of non-gui program in guiwithout socketschanges in the original programor blocking the gui of coursein many casesif you have to work this hard to add gui anyhowyou might as well just make your script traditional gui program with main window and event loop furthermorethe guis we've coded in this section are limited to displaying another program' outputsometimes the gui may have to do more for many programsthoughthe general separation of display and program logic provided by the spawned gui model can be an advantage--it' easier to understand both parts if they are not mixed together we'll learn more about sockets in the next part of the bookso you should consider parts of this discussion something of preview as we'll seethings start to become more and more interesting when we start combining guisthreadsand network sockets before we dothoughthe next rounds out the purely gui part of this book by applying the widgets and techniques we've learned in more realistically scaled programs and before thatthe next section wraps up here with preview of some of the more ways to add guis to non-gui code
5,232
the pydemos and pygadgets launchers to close out this let' explore the implementations of the two guis used to run major book examples the following guispydemos and pygadgetsare simply guis for launching other gui programs in factwe've now come to the end of the demo launcher story--both of the new programs here interact with modules that we met earlier in part iilaunchmodes py starts independent python programs portably launcher py finds programsand ultimately runs both pydemos and pygadgets when used by the self-configuring top-level launcher scripts launchbrowser pyw spawns web browsers portably to open local or remote pages see part ii (especially the ends of and for links to the code for these modules the programs introduced here add the gui components to the program-launching system--they simply provide easy-to-use pushbuttons that spawn most of the larger examples in this text when pressed both of these scripts also assume that they will be run with the current working directory set to their directory (they hardcode paths to other programs relative to thateither click on their names in file explorer or run them from command-line shell after cd to the top-level pp examples root directory these scripts could allow invocations from other directories by prepending an environment variable' value to program script pathsbut they were really designed to be run only out of the pp root because these demo launchers are long programsin the interest of space and time only their crucial and representative parts are listed in this bookas usualsee the examples package distribution for the portions omitted here pydemos launcher bar (mostly externalthe pydemos script constructs bar of buttons that run programs in demonstration modenot for day-to-day use use pydemos to show off python programs--it' much easier to press its buttons than to run command lines or fish through file explorer gui to find scripts you can use pydemos (and pygadgetsto start and interact with examples presented in this book--all of the buttons on this gui represent examples we will meet in later unlike when using the launch_pydemos and launch_pygadgets_bar scripts gui coding techniques
5,233
is set to include the directory containing the pp examples root directory if you wish to run the scripts here directlythey don' attempt to automatically configure your system or module import search paths to make this launcher bar even easier to rundrag it out to your desktop to generate clickable windows shortcut (do something similar on other systemssince this script hardcodes command lines for running programs elsewhere in the examples treeit is also useful as an index to major book examples figure - shows what pydemos looks like when run on windowsalong with some of the demos it launches--pydemos is the vertical button bar on the rightit looks slightly different but works the same on linux figure - pydemos with its pop ups and few demos the source code that constructs this scene is listed in example - (its first page may differ slightly from that shown being edited in figure - due to last minute tweaks which engineers can' seem to avoidbecause pydemos doesn' present much that' new in terms of gui interface programmingthoughmuch of it has been removed hereagainsee the examples package for the remainder in shortits demobutton function simply attaches new button to the main windowspring-loaded to spawn python program when pressed to start programspydemos calls an instance of the launchmodes portablelauncher object we met at the end of --its role as tkinter callback handler here is why function-call operation is used to kick off the launched program the pydemos and pygadgets launchers
5,234
description of the last demo spawnedand links pop up containing radio buttons that open local web browser on book-related sites when pressedthe info pop up displays simple message line and changes its font every second to draw attention to itselfsince this can be bit distractingthe pop up starts out iconified (click the info button to see or hide itthe links pop up' radio buttons are much like hyperlinks in web pagebut this gui isn' browserwhen the links pop up is pressedthe portable launch browser script mentioned in part ii is used to find and start web browser used to connect to the relevant siteassuming you have an internet connection this in turn uses python' webbrowser modules today the windows module we coded earlier in this (example - is used to give this gui' windows blue "pyiconinstead of the standard red "tk the pydemos gui also comes with "codebuttons to the right of each demo' buttonwhich open the source files that implement the associated example these files open in pop-up versions of the pyedit text editor that we'll meet in figure - captures some of these code viewer windows in actionresized slightly for display here for the web-based examples opened by the last two demo buttons in the launcherthis gui also attempts to spawn locally running web server for web-based demos not shown running here (we'll meet the server in for this editionthe web servers are spawned only when the corresponding web demo button is first selected (not on pydemos startup)and the web servers generate pop-up command prompt window on windows to monitor server status pydemos runs on windowsmacsand linuxbut that' largely due to the inherent portability of both python and tkinter for more detailsconsult the sourcewhich is shown in part in example - example - pp \pydemos pyw (external""###############################################################################pydemos pyw programming python nd rdand th editions (pp ) -- -- version ( )april ' updated to run under python xand spawn local web servers for web demos only on first demo button selection version ( )march ' add source-code file viewer buttonsadd new demos (pyphotopymailgui)spawn locally running web servers for the browser-based demosadd window iconsand probably more 've forgotten launch major python+tk gui examples from the bookin platform-neutral way this file also serves as an index to major program examplesthough many book gui coding techniques
5,235
examples aren' gui-basedand so aren' listed here also seepygadgets pya simpler script for starting programs in non-demo mode that you wish to use on regular basis pygadgets_bar pywwhich creates button bar for starting all pygadgets programs on demandnot all at once launcher py for starting programs without environment settings--finds pythonsets pythonpathetc launch_pyw for starting pydemos and pygadgets with launcher py--run these for quick look launchbrowser pyw for running example web pages with an automatically located web browser readme-pp txtfor general examples information caveatthis program tries to start locally running web server and web browser automaticallyfor web-based demosbut does not kill the server ###############################################################################""code omittedsee examples package ###############################################################################start building main gui windows ###############################################################################from pp gui tools windows import mainwindow from pp gui tools windows import popupwindow root mainwindow('pp demos ' tk with icontitlequit same but topleveldiff quit the pydemos and pygadgets launchers
5,236
stat popupwindow('pp demo info'stat protocol('wm_delete_window'lambda: ignore wm delete info label(stattext 'select demo'font=('courier' 'italic')padx= pady= bg='lightblue'info pack(expand=yesfill=both###############################################################################add launcher buttons with callback objects ###############################################################################from pp gui texteditor texteditor import texteditormainpopup demo launcher class class launcher(launchmodes portablelauncher)def announce(selftext)info config(text=textdef viewer(sources)for filename in sourcestexteditormainpopup(rootfilenameloadencode='utf- 'use wrapped launcher class customize to set gui label as pop up in this process else pyedit may ask eachdef demobutton(namewhatdoitcode)""add buttons that runs doit command-lineand open all files in codedoit button retains state in an objectcode in an enclosing scope""rowfrm frame(rootrowfrm pack(side=topexpand=yesfill=bothb button(rowfrmbg='navy'fg='white'relief=ridgeborder= config(text=namewidth= command=launcher(whatdoit) pack(side=leftexpand=yesfill=bothb button(rowfrmbg='beige'fg='navy' config(text='code'command=(lambdaviewer(code)) pack(side=leftfill=both###############################################################################tkinter gui demos some use network connections ###############################################################################demobutton(name='pyedit'what='text file editor'edit myself doit='gui/texteditor/texteditor py pydemos pyw'assume in cwd code=['launchmodes py''tools/find py''gui/tour/scrolledlist py'show in pyedit viewer 'gui/shellgui/formrows py'last top of stacking 'gui/tools/guimaker py''gui/texteditor/textconfig py''gui/texteditor/texteditor py'] gui coding techniques
5,237
what='image slideshowplus note editor'doit='gui/slideshow/slideshowplus py gui/gifs'code=['gui/texteditor/texteditor py''gui/slideshow/slideshow py''gui/slideshow/slideshowplus py']code omittedsee examples package ###############################################################################toggle info message box font once second ###############################################################################def refreshme(infoncall)slant ['normal''italic''bold''bold italic'][ncall info config(font=('courier' slant)root after( (lambdarefreshme(infoncall+ )###############################################################################unhide/hide status box on info clicks ###############################################################################stat iconify(def oninfo()if stat state(='iconic'stat deiconify(elsestat iconify(was 'normal###############################################################################finish building main guistart event loop ###############################################################################def onlinks()code omittedsee examples package button(roottext='info'command=oninfopack(side=topfill=xbutton(roottext='links'command=onlinkspack(side=topfill=xbutton(roottext='quit'command=root quitpack(side=bottomfill=xrefreshme(info start toggling root mainloop(pygadgets launcher bar the pygadgets script runs some of the same programs as pydemosbut for realpractical usenot as demonstrations both scripts use launchmodes to spawn other programsand display bars of launcher buttonsbut pygadgets is bit simpler because its task is more focused pygadgets also supports two spawning modes--it can either start canned list of programs immediately and all at onceor display gui for running each program on demand figure - shows the launch bar gui made in on-demand mode when it first startspydemos and pygadgets can be run at the same timeand both grow with their window if resized (try it on your own to see howthe pydemos and pygadgets launchers
5,238
because of its different rolepygadgets takes more data-driven approach to building the guiit stores program names in list and steps through it as needed instead of using sequence of precoded demobutton calls the set of buttons on the launcher bar gui in figure - for exampledepends entirely upon the contents of the programs list the source code behind this gui is listed in example - it' not much because it relies on other modules we wrote earlier to work most of its magiclaunchmodes for program spawnswindows for window icons and quitsand launchbrowser for web browser starts pygadgets gets clickable shortcut on my desktop and is usually open on my machines use to gain quick access to python tools that use on daily basis-text editorscalculatorsemail and photo toolsand so on--all of which we'll meet in upcoming to customize pygadgets for your own usesimply import and call its functions with program command-line lists of your own or change the mytools list of spawnable programs near the end of this file this is pythonafter all example - pp \pygadgets py ""#############################################################################start various examplesrun me at start time to make them always available this file is meant for starting programs you actually wish to usesee pydemos for starting python/tk demos and more details on program start options windows usage notethis is pyto show messages in console window when run or clicked (including second pause to make sure it' visible while gadgets start if clickedto avoid windows console pop uprun with the 'pythonwprogram (not 'python')rename to pywsuffixmark with 'run minimizedwindow propertyor spawn elsewhere (see pydemos#############################################################################""import systimeostime from tkinter import from launchmodes import portablelauncher from gui tools windows import mainwindow reuse program start class reuse window toolsiconquit def runimmediate(mytools)""launch gadget programs immediately ""print('starting python/tk gadgets 'msgs to stdout (poss temp gui coding techniques
5,239
portablelauncher(namecommandline)(print('one moment please 'if sys platform[: ='win'for in range( )time sleep( )print( ( + )call now to start now windowskeep console secs def runlauncher(mytools)""pop up simple launcher bar for later use ""root mainwindow('pygadgets pp 'or root tk(if prefer for (namecommandlinein mytoolsb button(roottext=namefg='black'bg='beige'border= command=portablelauncher(namecommandline) pack(side=leftexpand=yesfill=bothroot mainloop(mytools ('pyedit'('pycalc'('pyphoto'('pymail'('pyclock'('pytoe'('pyweb''gui/texteditor/texteditor py')'lang/calculator/calculator py')'gui/pil/pyphoto py gui/pil/images')'internet/email/pymailgui/pymailgui py')'gui/clock/clock py -size -bg white-picture gui/gifs/pythonpowered gif')'ai/tictactoe/tictactoe py-mode minimax -fg white -bg navy')'launchbrowser pyw-live index html learning-python com')#-live pyinternetdemos html localhost: ')#-file')pyinternetdemos assumes local server started if __name__ ='__main__'prestarttoolbar truefalse if prestartrunimmediate(mytoolsif toolbarrunlauncher(mytoolsby defaultpygadgets starts programs immediately when it is run to run pygadgets in launcher bar mode insteadexample - simply imports and calls the appropriate function with an imported program list because it is pyw fileyou see only the launcher bar gui it constructs initiallynot dos console streams window--nice for regular usebut not if you want to see error messages (use pyexample - pp \pygadgets_bar pyw ""run pygadgets toolbar onlyinstead of starting all the gadgets immediatelyfilename avoids dos pop up on windowsrename to pyto see console messages""import pygadgets pygadgets runlauncher(pygadgets mytoolsthe pydemos and pygadgets launchers
5,240
on demand on many platformsyou can drag this out as shortcut on your desktop for easy access this way you can also run script like this at your system' startup to make it always available (and to save mouse clickfor instanceon windowssuch script might be automatically started by adding it to your startup folderand on unix and its kin you can automatically start such script by spawning it with command line in your system startup scripts after windows has been started whether run via shortcuta file explorer clicka typed command lineor other meansthe pygadgets launcher bar near the center of figure - appears figure - pygadgets launcher bar with gadgets of coursethe whole point of pygadgets is to spawn other programs pressing on its launcher bar' buttons starts programs like those shown in the rest of figure - but if you want to know more about thoseyou'll have to turn the page and move on to the next gui coding techniques
5,241
complete gui programs "pythonopen sourceand camarosthis concludes our look at building guis with python and its standard tkinter libraryby presenting collection of realistic gui programs in the preceding four we met all the basics of tkinter programming we toured the core set of widgets--python classes that generate devices on computer screen and respond to user events--and we studied handful of advanced gui programming techniquesincluding automation toolsredirection with sockets and pipesand threading hereour focus is on putting those widgets and techniques together to create more useful guis we'll studypyedit text editor program pyphoto thumbnail photo viewer pyview an image slideshow pydraw painting program pyclock graphical clock pytoe simple tic-tac-toe gamejust for funall of the larger examples in this book have py at the start of their names this is by convention in the python world if you shop around at toopyopengl ( python interface to the opengl graphics library)pygame ( python game development kit)and many more ' not sure who started this patternbut it has turned out to be more or less subtle way to advertise programming language preferences to the rest of the open source world pythonistas are nothing if not pysubtle
5,242
of python programs that really use for instancethe text editor and clock guis that we'll meet here are day-to-day workhorses on my machines because they are written in python and tkinterthey work unchanged on my windows and linux machinesand they should work on macs too since these are pure python scriptstheir future evolution is entirely up to their users-once you get handle on tkinter interfaceschanging or augmenting the behavior of such programs by editing their python code is snap although some of these examples are similar to commercially available programs ( pyedit is reminiscent of the windows notepad accessory)the portability and almost infinite configurability of python scripts can be decided advantage examples in other later in the bookwe'll meet other tkinter gui programs that put good face on specific application domains for instancethe following larger gui examples show up in later alsopymailgui comprehensive email client (pyform (mostly externalpersistent object table viewer (pytree (mostly externaltree data structure viewer and pycalc customizable calculator widget (smaller examplesincluding ftp and file-transfer guispop up in the internet part as well most of these programs see regular action on my desktoptoo because gui libraries are general-purpose toolsthere are very few domains that cannot benefit from an easy-to-useeasy-to-programand widely portable user interface coded in python and tkinter beyond the examples in this bookyou can also find higher-level gui toolkits for pythonsuch as the pmwtixand ttk packages introduced in some such systems build upon tkinter to provide compound components such as notebook tabbed widgetstree viewsand balloon pop-up help in the next part of the bookwe'll also explore programs that build user interfaces in web browsersinstead of tkinter-- very different way of approaching the user interface experience although web browser interfaces have been historically limited in functionality and slowed by network latencywhen combined with the rich internet application (riatoolkits mentioned at the start of browser-based guis today complete gui programs
5,243
software complexity and dependencies especially for highly interactive and nontrivial interfacesthoughstandalone/desktop tkinter guis can be an indispensable feature of almost any python program you write the programs in this underscore just how far python and tkinter can take you this strategy as for all case-study in this textthis one is largely learn-by-example exercisemost of the programs here are listed with minimal details along the wayi'll highlight salient points and underscore new tkinter features that examples introducebut 'll also assume that you will study the listed source code and its comments for more information once we reach the level of complexity demonstrated by programs herepython' readability becomes substantial advantage for programmers (and writers of booksall of this book' gui examples are available in source code form in the book' examples distribution described in the preface because 've already shown the interfaces these scripts employthis section consists mostly of screenshotsprogram listingsand few brief words describing some of the most important aspects of these programs in other wordsthis is self-study sectionread the sourcerun the examples on your own computerand refer to the previous for further details on the code listed here some of these programs may also be accompanied in the book examples distribution by alternative or experimental implementations not listed heresee the distribution for extra code examples finallyi want to remind you that all of the larger programs listed in the previous sections can be run from the pydemos and pygadgets launcher bar guis that we met at the end of although will try hard to capture some of their behavior in screenshots hereguis are event-driven systems by natureand there is nothing quite like running one live to sample the flavor of its user interactions because of thatthe launcher bars are really supplement to the material in this they should run on most platforms and are designed to be easy to start (see the top-level readmepp txt file for hintsyou should go there and start clicking things immediately if you haven' done so already open source software and camaros some of the gui programs in this as well as the rest of the bookare analogous to utilities found on commonly used operating systems like windows for instancewe'll meet calculatorstext editorsimage viewersclocksemail clientsand more unlike most utilitiesthoughthese programs are portable--because they are written in python with tkinterthey will work on all major platforms (windowsunix/linuxand macsperhaps more importantbecause their source code is availablethey can be scripted--you can change their appearance or function however you likejust by writing or modifying little python code "pythonopen sourceand camaros
5,244
of us who remember time when it was completely normal for car owners to work on and repair their own automobiles still fondly remember huddling with friends under the hood of camaro in my youthtweaking and customizing its engine with little workwe could make it as fastflashyand loud as we liked moreovera breakdown in one of those older cars wasn' necessarily the end of the world there was at least some chance that could get the car going again on my own that' not quite true today with the introduction of electronic controls and diabolically cramped engine compartmentscar owners are usually better off taking their cars back to the dealer or another repair professional for all but the simplest kinds of changes by and largecars are no longer user-maintainable products and if have breakdown in my shiny new ridei' probably going to be completely stuck until an authorized repair person can get around to towing and fixing it like to think of the closed and open software models in the same terms when use microsoft-provided programs such as notepad and outlooki' stuck with the feature set that large company dictatesas well as any bugs that it may harbor but with programmable tools such as pyedit and pymailguii can still get under the hood can add featurescustomize the systemand work my way out of any lurking bugs and can do so long before the next microsoft patch or release is available ' no longer dependent on self-interested company to support--or even to continue producing-the tools use of coursei' still dependent on python and whatever changes it may dictate over time (and after updating two , page books for python xi can say with some confidence that this dependency isn' always completely trivialhaving all the source code for every layer of the tools you depend onthoughis still powerful last resortand major net win as an added bonusit fosters robustness by providing built-in group of people to test and hone the system at the end of the dayopen source software and python are as much about freedom as they are about cost usersnot an arbitrarily far-removed companyhave the final say not everyone wants to work on his own carof course on the other handsoftware tends to fail much more often than carsand python scripting is generally less greasy than auto mechanics pyedita text editor program/object in the last few decadesi've typed text into lot of programs most were closed systems ( had to live with whatever decisions their designers made)and many ran on only one platform the pyedit program presented in this section does better on both countsaccording to its own tools/info optionpyedit implements full-featuredgraphical text editor program in total of , new lines of portable python codeincluding whitespace and commentsdivided between , lines in the main file and lines of configuration module settings (at releaseat least--final sizes may vary slightly in future revisionsdespite its relatively modest sizeby systems programming standards complete gui programs
5,245
most of the examples in this book pyedit supports all the usual mouse and keyboard text-editing operationscut and pastesearch and replaceopen and saveundo and redoand so on but reallypyedit is bit more than just another text editor--it is designed to be used as both program and library componentand it can be run in variety of rolesstandalone mode as standalone text-editor programwith or without the name of file to be edited passed in on the command line in this modepyedit is roughly like other textediting utility programs ( notepad on windows)but it also provides advanced functions such as running python program code being editedchanging fonts and colors"grepthreaded external file searcha multiple window interfaceand so on more importantbecause it is coded in pythonpyedit is easy to customizeand it runs portably on windowsx windowsand macintosh pop-up mode within new pop-up windowallowing an arbitrary number of copies to appear as pop ups at once in program because state information is stored in class instance attributeseach pyedit object created operates independently in this mode and the nextpyedit serves as library object for use in other scriptsnot as canned application for example' pymailgui employs pyedit in pop-up mode to view email attachments and raw textand both pymailgui and the preceding pydemos display source code files this way embedded mode as an attached componentto provide text-editing widget for other guis when attachedpyedit uses frame-based menu and can optionally disable some of its menu options for an embedded role for instancepyview (later in this uses pyedit in embedded mode this way to serve as note editor for photosand pymailgui (in attaches it to get an email text editor for free while such mixed-mode behavior may sound complicated to implementmost of pyedit' modes are natural byproduct of coding guis with the class-based techniques we've seen in the last four running pyedit pyedit sports lots of featuresand the best way to learn how it works is to test-drive it for yourself--you can run it by starting the main file texteditor pyby running files texteditornoconsole pyw or pyedit pyw to suppress console window on windowsor from the pydemos and pygadgets launcher bars described at the end of (the launchers themselves live in the top level of the book examples directory treeto give you sampling of pyedit' interfacesfigure - shows the main pyedita text editor program/object
5,246
window' default appearance running in windows after opening pyedit' own source code file the main part of this window is text widget objectand if you read ' coverage of this widgetpyedit text-editing operations will be familiar it uses text markstagsand indexesand it implements cut-and-paste operations with the system clipboard so that pyedit can paste data to and from other applicationseven after an application of origin is closed both vertical and horizontal scroll bars are cross-linked to the text widgetto support movement through arbitrary files menus and toolbars if pyedit' menu and toolbars look familiarthey should--pyedit builds the main window with minimal code and appropriate clipping and expansion policies by mixing in the guimaker class we coded in the prior (example - the toolbar at the bottom contains shortcut buttons for operations tend to use most oftenif my preferences don' match yourssimply change the toolbar list in the source code to show the buttons you want (this is pythonafter allas usual for tkinter menusshortcut key combinations can be used to invoke menu options quicklytoo--press alt plus all the underlined keys of entries along the path to the desired action menus can also be torn off at their dashed line to provide quick access to menu options in new top-level windows (handy for options without toolbar buttons complete gui programs
5,247
pyedit pops up variety of modal and nonmodal dialogsboth standard and custom figure - shows the custom and nonmodal changefontand grep dialogsalong with standard dialog used to display file statistics (the final line count may varyas tend to tweak code and comments right up until final draftfigure - pyedit with colorsa fontand few pop ups the main window in figure - has been given new foreground and background colors (with the standard color selection dialog)and new text font has been selected from either the font dialog or canned list in the script that users can change to suit their preferences (this is pythonafter allother toolbar and menu operations generally use popped-up standard dialogswith few new twists for instancethe standard file open and save selection dialogs in pyedit use object-based interfaces to remember the last directory visitedso you don' have to navigate there every time running program code one of the more unique features of pyedit is that it can actually run python program code that you are editing this isn' as hard as it may sound either--because python provides built-ins for compiling and running code strings and for launching programspyedit simply has to make the right calls for this to work for exampleit' easy to code simple-minded python interpreter in pythonusing code like the following (see file pyedita text editor program/object
5,248
you need bit more to handle multiple-line statements and expression result displaysread and run python statement stringslike pyedit' run code menu option namespace {while truetryline input('single-line statements only except eoferrorbreak elseexec(linenamespaceor eval(and print result depending on the user' preferencepyedit either does something similar to this to run code fetched from the text widget or uses the launchmodes module we wrote at the end of to run the code' file as an independent program there are variety of options in both schemes that you can customize as you like (this is pythonafter allsee the onruncode method for details or simply edit and run some python code in pyedit on your own to experiment when edited code is run in nonfile modeyou can view its printed output in pyedit' console window as we footnoted about eval and exec in also make sure you trust the source of code you run this wayit has all permissions that the python process does multiple windows pyedit not only pops up multiple special-purpose windowsit also allows multiple edit windows to be open concurrentlyin either the same process or as independent programs for illustrationfigure - shows three independently started instances of pyeditresized and running with variety of color schemes and fonts since these are separate programsclosing any of these does not close the others this figure also captures pyedit torn-off menus at the bottom and the pyedit help pop up on the right the edit windowsbackgrounds are shades of greenredand blueuse the tools menu' pick options to set colors as you like since these three pyedit sessions are editing python source-coded textyou can run their contents with the run code option in the tools pull-down menu code run from files is spawned independentlythe standard streams of code run not from file ( fetched from the text widget itselfare mapped to the pyedit session' console window this isn' an ide by any meansit' just something added because found it to be useful it' nice to run code you're editing without fishing through directories to run multiple edit windows in the same processuse the tools menu' clone option to open new empty window without erasing the content of another figure - shows the single-process scene with window and its clonealong with pop-ups related to the search menu' grep optiondescribed in the next section-- tool that walks directory trees in parallel threadscollecting files of matching names that contain search stringand opening them on request in figure - grep has produced an input dialog complete gui programs
5,249
matches listand new pyedit window positioned at match after double-click in the list box another pop up appears while grep search is in progressbut the gui remains fully activein factyou can launch new greps while others are in progress notice how the grep dialog also allows input of unicode encodingused to decode file content in all text files visited during the tree searchi'll describe how this works in the changes section aheadbut in most casesyou can accept the prefilled platform default encoding for more funuse this dialog to run grep in directory :\python for all py files that contain string %-- quick look at how common the original string formatting expression iseven in python ' own library code though not all are related to string formattingmost appear to be per message printed to standard output on grep thread exitthe string '%(which includes substitution targetsoccurs , timesand the string (with surrounding spaces to better narrow in on operator appearancesappears , timesincluding in the installed pil extension--not exactly an obscure language toolhere are the messages printed to standard output during this searchmatches appear in list box windowerrors may vary per encoding type unicode error inc:\python \lib\lib to \tests\data\different_encoding py unicode error inc:\python \lib\test\test_doctest py unicode error inc:\python \lib\test\test_tokenize py matches for pyedita text editor program/object
5,250
pyedit generates additional pop-up windows--including transient goto and find dialogscolor selection dialogsdialogs that appear to collect arguments and modes for run codeand dialogs that prompt for entry of unicode encoding names on file open and save if pyedit is configured to ask (more on this aheadin the interest of spacei'll leave most other such behavior for you to witness live prominently new in this editionthoughand subject to user configurationspyedit may ask for file' unicode encoding name when opening filesaving new file begun from scratchor running save as operation for examplefigure - captures the scene after 've opened file encoded in chinese character set scheme and pressed open again to open new file encoded in russian encoding the encoding name input dialog shown in the figure appears immediately after the standard file selection dialog is dismissedand it is prefilled with the default encoding choice configured (an explicit setting or the platform' defaultthe displayed default can be accepted in most casesunless you know the file' encoding differs in generalpyedit supports any unicode character set that python and tkinter dofor opensdisplayand saves the text in figure - for instancewas encoding in specific chinese encoding in the file it came from ("gb for file email-part-gb an alternative utf- encoding of this text is available in the same directory (file email-part--gb --utf which works per the default windows encoding in pyedit and notepadbut the specific chinese encoding file requires the explicitly complete gui programs
5,251
entered encoding name to display properly in pyedit (and won' display correctly at all in notepadafter enter the encoding name for the selected file ("koi -rfor the file selected to openin the input dialog of figure - pyedit decodes and pops up the text in its display figure - show the scene after this file has been opened and 've selected the save as option in this window--immediately after file selection dialog is dismissedanother encoding input dialog is presented for the new fileprefilled with the known encoding from the last open or save as configuredsave reuses the known encoding automatically to write to the file againbut saveas always asks to allow for new onebefore trying defaults againi'll say more on the unicode/internationalization policies of pyedit in the next sectionwhen we discuss version changesin shortbecause user preferences can' be predicteda variety of policies may be selected by configuration finallywhen it' time to shut down for the daypyedit does what it can to avoid losing changes not saved when quit is requested for any edit windowpyedit checks for changes and verifies the operation in dialog if the window' text has been modified and not saved because there may be multiple edit windows in the same processwhen quit is requested in main windowpyedit also checks for changes in all other windows still openand verifies exit if any have been altered--otherwise the quit would close every window silently quits in pop-up edit windows destroy that window onlyso no cross-process check is made if no changes have been madequit requests in the gui close windows and programs silently other operations verify changes in similar ways pyedita text editor program/object
5,252
other pyedit examples and screenshots in this book for other screenshots showing pyedit in actionsee the coverage of the following client programspydemos in deploys pyedit pop-ups to show source-code files pyview later in this embeds pyedit to display image note files pymailgui in uses pyedit to display email texttext attachmentsand source the last of these especially makes heavy use of pyedit' functionality and includes screenshots showing pyedit displaying additional unicode text with internationalized character sets in this rolethe text is either parsed from messages or loaded from temporary fileswith encodings determined by mail headers pyedit changes in version (third editioni've updated this example in both the third and fourth editions of this book because this is intended to reflect realistic programming practiceand because this example reflects that way that software evolves over timethis section and the one following it provide quick rundown of some of the major changes made along the way to help you study the code complete gui programs
5,253
begin with the previous version' additions in the third editionpyedit was enhanced witha simple font specification dialog unlimited undo and redo of editing operations file modified tests whenever content might be erased or changed user configurations module here are some quick notes about these extensions font dialog for the third edition of the bookpyedit grew font input dialog-- simplethree-entrynonmodal dialog where you can type the font familysizeand styleinstead of picking them from list of preset options though functionalyou can find more sophisticated tkinter font selection dialogs in both the public domain and within the implementation of python' standard idle development gui (as mentioned earlierit is itself pythontkinter programundoredoand modified tests also new in the third editionpyedit supports unlimited edit undo and redoas well as an accurate modified check before quitopenrunand new actions to prompt for saves it now verifies exits or overwrites only if text has been changedinstead of always asking naively the underlying tk (or laterlibrary provides an apiwhich makes both these enhancements simple--tk keeps undo and redo stacks automatically they are enabled with the text widget' undo configuration option and are accessed with the widget methods edit_undo and edit_redo similarlyedit_reset clears the stacks ( after new file open)and edit_modified checks or sets the automatic text modified flag it' also possible to undo cuts and pastes right after you've done them (simply paste back from the clipboard or cut the pasted and selected text)but the new undo/redo operations are more complete and simpler to use undo was suggested exercise in the second edition of this bookbut it has been made almost trivial by the new tk api configuration module for usabilitythe third edition' version of pyedit also allows users to set startup configuration options by assigning variables in moduletextconfig py if present on the module search path when pyedit is imported or runthese assignments give initial values for fontcolorstext window sizeand search case sensitivity fonts and colors can be changed interactively in the menus and windows can be freely resizedso this is largely just convenience also note that this module' settings will be inherited by all instances of pyedit if it is importable in the client program--even when it is popup window or an embedded component of another application client applications pyedita text editor program/object
5,254
needs pyedit changes in version (fourth editionbesides the updates described in the prior sectionthe following additional enhancements were made for this current fourth edition of this bookpyedit has been ported to run under python and its tkinter library the nonmodal change and font dialogs were fixed to work better if multiple instance windows are openthey now use per-dialog state quit request in main windows now verifies program exit if any other edit windows in the process have changed contentinstead of exiting silently there' new grep menu option and dialog for searching external filessearches are run in threads to avoid blocking the gui and to allow multiple searches to overlap in time and support unicode text there was minor fix for initial positioning when text is inserted initially into newly created editorreflecting change in underlying libraries the run code option for files now uses the base file name instead of the full directory path after chdir to better support relative pathsallows for command-line arguments to code run from filesand inherits patch made in ' launchmodes which converts to in script paths in additionthis option always now runs an update between pop-up dialogs to ensure proper display perhaps most prominentlypyedit now processes files in such way as to support display and editing of text with arbitrary unicode encodingsto the extent allowed by the underlying tk gui library for unicode strings specificallyunicode is taken into account when opening and saving fileswhen displaying text in the guiand when searching files in directories the following sections provide additional implementation notes on these changes modal dialog state fix the change dialog in the prior version saved its entry widgets on the text editor objectwhich meant that the most recent change dialog' fields were used for every change dialog open this could even lead to program aborts for finds in an older change dialog window if newer ones had been closedsince the closed window' widgets had been destroyed--an unanticipated usage modewhich has been present since at least the second editionand which ' like to chalk up to operator errorbut which was really lesson in state retentionthe same phenomenon existed in the font dialog--its most recently opened instance stole the showthough its brute force exception handler prevented program aborts (it issued error pop ups insteadto fixthe change and font complete gui programs
5,255
could instead allow just one of each dialog to be openbut that' less functional cross-process change tests on quit though not quite as grievouspyedit also used to ignore changes in other open edit windows on quit in main windows as policyon quit in the guipop-up edit windows destroy themselves onlybut main edit windows run tkinter quit to end the entire program although all windows verify closes if their own content has changedother edit windows were ignored in the prior version--quitting main window could lose changes in other windows closed on program exit to do betterthis version keeps list of all open managed edit windows in the processon quit in main windows it checks them all for changesand verifies exit if any have changed this scheme isn' foolproof (it doesn' address quits run on widgets outside pyedit' scope)but it is an improvement more ultimate solution probably involves redefining or intercepting tkinter' own quit method to avoid getting too detailed herei'll defer more on this topic until later in this section (see the event coverage ahead)also see the relevant comments near the end of pyedit' source file for implementation notes new grep dialogthreaded and unicode-aware file tree search in additionthere is new grep option in the search pull-down menuwhich implements an external file search tool this tool scans an entire directory tree for files whose names match patternand which contain given search string names of matches are popped up in new nonmodal scrolled list windowwith lines that identify all matches by filenameline numberand line content clicking on list item opens the matched file in new nonmodal and in-process pyedit pop-up edit window and automatically moves to and selects the line of the match this achieves its goal by reusing much code we wrote earlierthe find utility we wrote in to do its tree walking the scrolled list utility we coded in for displaying matches the form row builder we wrote in for the nonmodal input dialog the existing pyedit pop-up window mode logic to display matched files on request the existing pyedit go-to callback and logic to move to the matched line in file grep threading model to avoid blocking the gui while files are searched during tree walksgrep runs searches in parallel threads this also allows multiple greps to be running at once and to overlap in time arbitrarily (especially useful if you grep in larger treessuch as python' own library or full source treesthe standard threadsqueuesand after timer loops technique we learned in is applied here--non-gui producer threads find matches and place them on queue to be detected by timer loop in the main gui thread pyedita text editor program/object
5,256
own threadtimer loopand queue there may be multiple threads and loops runningand there may be other unrelated threadsqueuesand timer loops in the process for instancean attached pyedit component in ' pymailgui program can run grep threads and loops of its ownwhile pymailgui runs its own email-related threads and queue checker each loop' handler is dispatched independently from the tkinter event stream processor because of the simpler structure herethe general thread tools callback queue of is not used here for more notes on grep thread implementation see the source code aheadand compare to file _unthreadedtexteditor py in the examples packagea nonthreaded version of pyedit grep unicode model if you study the grep option' codeyou'll notice that it also allows input of tree-wide unicode encodingand catches and skips any unicode decoding error exceptions generated both when processing file content and walking the tree' filenames as we learned in and files opened in text mode in python must be decodable per provided or platform default unicode encoding this is particular problematic for grepas directory trees may contain files of arbitrarily mixed encoding types in factit' common on windows to have files with content in asciiutf- and utf- form mixed in the same tree (notepad' "ansi,"utf- ,and "unicode")and even others in trees that contain content obtained from the web or email opening all these with utf- would trigger exceptions in python xand opening all these in binary mode yields encoded text that will likely fail to match search key string technicallyto compare at allwe' still have to decode the bytes read to text or encode the search key string to bytesand the two would only match if the encodings used both succeed and agree to allow for mixed encoding treesthe grep dialog opens in text mode and allows an encoding name to be input and used to decode file content for all files in the tree searched this encoding name is prefilled with the platform content default for convenienceas this will often suffice to search trees of mixed file typesusers may run multiple greps with different encoding names the names of files searched might fail to decode as wellbut this is largely ignored in the current releasethey are assumed to satisfy the platform filename conventionand end the search if they don' (see and for more on filename encoding issues in python itselfas well as the find walker reused herein additiongrep must take care to catch and recover from encoding errorssince some files with matching names that it searches might still not be decodable per the input encodingand in fact might not be text files at all for examplesearches in python ' standard library (like the example grep for described earlierrun into handful of files which do not decode properly on my windows machine and would otherwise crash pyedit binary files which happen to match the filename patterns would fare even worse complete gui programs
5,257
or opening files in binary modesince grep might not be able to interpret some of the files it visits as text at allit takes the former approach reallyopening even text files in binary mode to read raw byte strings in mimics the behavior of text files in xand underscores why forcing programs to deal with unicode is sometimes good thing--binary mode avoids decoding exceptionsbut probably shouldn'tbecause the still-encoded text might not work as expected in this caseit might yield invalid comparison results for more details on grep' unicode supportand set of open issues and options surrounding itsee the source code listed ahead for suggested enhancementsee also the re pattern matching module in -- tool we could use to search for patterns instead of specific strings update for initial positioning also in this versiontext editor updates itself before inserting text into its text widget at construction time when it is passed an initial file name in its loadfirst argument sometime after the third edition and python either tk or tkinter changed such that inserting text before an update call caused the scroll position to be off by one--the text editor started with line at its top in this mode instead of line this also occurs in the third edition' version of this example under python but not adding an update correctly positions at line initially obscure but true in the real world of library dependencies!clients of the classes here should also update before manually inserting text into newly created (or packedtext editor object for accurate positioningpyview later in this as well as pymailgui in now do pyedit doesn' update itself on every constructionbecause it may be created early byor even hidden inan enclosing gui (for instancethis would show half-complete window in pyviewmoreoverpyedit could automatically update itself at the start of setalltext instead of requiring this step of clientsbut forced update is required only once initially after being packed (not before each text insertion)and this too might be an undesirable side effect in some conceivable use cases as rule of thumbadding unrelated operations to methods this way tends to limit their scope improvements for running code the run code option in the tools menu was fixed in three ways that make it more useful for running code being edited from its external filerather than in-processinterestinglypython' own idle text editor in python suffers from two of the same bugs described here and resolved in this edition' pyedit--in idle positions at line instead of line on file opensand its external files search (similar to pyedit' grepcrashes on unicode decoding errors when scanning the python standard librarycausing idle to exit altogether insert snarky comment about the shoemaker' children having no shoes here pyedita text editor program/object
5,258
code accuratepyedit now strips off any directory path prefix in the file' name before launching itbecause its original directory path may no longer be valid if it is relative instead of absolute for instancepaths of files opened manually are absolutebut file paths in pydemos' code pop ups are all relative to the example package root and would fail after chdir pyedit now correctly uses launcher tools that support command-line arguments for file mode on windows pyedit inherits fix in the underlying launchmodes module that changes forward slashes in script path names to backslashes (though this was later made moot point by stripping relative path prefixespyedit gets by with forward slashes on windows because open allows thembut some windows launch tools do not additionallyfor both code run from files and code run in memorythis version adds an update call between pop-up dialogs to ensure that later dialogs appear in all cases (the second occasionally failed to pop up in rare contextseven with these fixesrun code is useful but still not fully robust for exampleif the edited code is not run from fileit is run in-process and not spawned off in threadand so may block the gui it' also not clear how best to handle import paths and directories for files run in nonfile modeor whether this mode is worth retaining in general improve as desired unicode (internationalizedtext support finallybecause python now fully supports unicode textthis version of pyedit doestoo--it allows text of arbitrary unicode encodings and character sets to be opened and saved in filesviewed and edited in its guiand searched by its directory search utility this support is reflected in pymailgui' user interface in variety of waysopens must ask the user for an encoding (suggesting the platform defaultif one is not provided by the client application or configuration saves of new files must ask for an encoding if one is not provided by configuration display and edit must rely on the gui toolkit' own support for unicode text grep directory searches must allow for input of an encoding to apply to all files in the tree and skip files that fail to decodeas described earlier the net result is to support internationalized text which may differ from the platform' default encoding this is particularly useful for text files fetched over the internet by email or ftp ' pymailguifor exampleuses an embedded pyedit object to view text attachments of arbitrary origin and encoding the grep utility' unicode support was described earlierthe remainder of this model essentially reduces to file opens and savesas the next section describes unicode file and display model because strings are always unicode code-point strings once they are created in memoryunicode support really means supporting arbitrary encodings for text files when they are read and written recall that text can be stored in complete gui programs
5,259
formats when read and encoded to them when written unless text is always stored in files using the platform' default encodingwe need to know which encoding to useboth to load and to save to make this workpyedit uses the approaches described in detail in which we won' repeat in full here in briefthoughtkinter' text widget accepts content as either str and bytes and always returns it as str pyedit maps this interface to and from python file objects as followsinput files (opendecoding from file bytes to strings in general requires the name of an encoding type that is compatible with data in the fileand fails if the two do not agree ( decoding -bit data to asciiin some casesthe unicode type of the text file to be opened may be unknown to loadpyedit first tries to open input files in text mode to read str stringsusing an encoding obtained from variety of sources-- method argument for known type ( from headers of email attachments or source files opened by demos) user dialog replya configuration module settingand the platform default whenever prompting users for an open encodingthe dialog is prefilled with the first choice implied by the configuration fileas default and suggestion if all these encoding sources fail to decodethe file is opened in binary mode to read text as bytes without an encoding nameeffectively delegating encoding issues to the tk gui libraryin this caseany \ \ end-lines are manually converted to \ on windows so they correctly display and save later binary mode is used only as last resortto avoid relying on tk' policies and limited character set support for raw bytes text processing the tkinter text widget returns its content on request as str stringsregardless of whether str or bytes were inserted because of thatall text processing of content fetched from the gui is conducted in terms of str unicode strings here output files (savesave asencoding from strings to file bytes is generally more flexible than decoding and need not use the same encoding from which the string was decodedbut can also fail if the chosen scheme is too narrow to handle the string' content ( encoding -bit text to asciito savepyedit opens output files in text mode to perform end-line mappings and unicode encoding of str content an encoding name is again fetched from one of variety of sources--the same encoding used when the file was first opened or saved (if any) user dialog replya configuration module settingand the platform default unlike openssave dialogs that prompt for encodings are prefilled with the known encoding if there is one as suggestionotherwisethe dialog is prefilled with the next configured choice as defaultas for opens pyedita text editor program/object
5,260
other options are selected in configuration module assignments since it' impossible to predict all possible use case scenariospyedit takes liberal approachit supports all conceivable modesand allows the way it obtains file encodings to be heavily tailored by users in the package' own textconfig module it attempts one encoding name source after anotherif enabled in textconfiguntil it finds an encoding that works this aims to provide maximum flexibility in the face of an uncertain unicode world for examplesubject to settings in the configuration filesaves reuse the encoding used for the file when it was opened or initially savedif known both new files begun from scratch (with new or manual text insertsand files opened in binary mode as last resort have no known encoding until savedbut files previously opened as text do also subject to configuration file settingswe may prompt users for an encoding on save as (and possibly savebecause they may have preference for new files they create we also may prompt when opening an existing filebecause this requires its current encodingalthough the user may not always know what this is ( files fetched over the internet)the user may wish to provide it in others rather than choosing course of action in such caseswe rely on user configuration all of this is really relevant only to pyedit clients that request an initial file load or allow files to be opened and saved in the gui because content can be inserted as str or bytesclients can always open and read input files themselves prior to creating text editor object and insert the text manually for viewing moreoverclients can fetch content manually and save in any fashion preferred such manual approach might prove useful if pyedit' polices are undesirable for given context since the text widget always returns content as strthe rest of this program is unaffected by the data type of text inserted keep in mind that these policies are still subject to the unicode support and constraints of the underlying tk gui toolkitas well as python' tkinter interface to it although pyedit allows text to be loaded and saved in arbitrary unicode encodingsit cannot guarantee that the gui library will display such text as you wish that iseven if we get the unicode story right on the python side of the fencewe're still at the mercy of other software layers which are beyond the scope of this book tk seems to be robust across wide range of character sets if we pass it already decoded python str unicode strings (see the internationalization support in ' pymailgui for samples)but your mileage might vary unicode options and choices also keep in mind that the unicode policies adopted in pyedit reflect the use cases of its sole current userand have not been broadly tested for ergonomics and generalityas book examplethis doesn' enjoy the built-in test environment of open source projects other schemes and source orderings might work welltooand it' impossible to guess the preferences of every user in every context for instance complete gui programs
5,261
vice-versa perhaps we also should always ask the user for an encoding as last resortirrespective of configuration settings for saveswe could also try to guess an encoding to apply to the str content ( try utf- latin- and other common types)but our guess may not be what the user has in mind it' likely that users will wish to save file in the same encoding with which it was first openedor initially saved if started from scratch pyedit provides support to do soor else the gui might ask for given file' encoding more than once howeverbecause some users might also want to use save again to overwrite the same file with different encodingthis can be disabled in the configuration module the latter role might sound like save asbut the next bullet explains why it may not similarlyit' not obvious if save as should also reuse the encoding used when the file was first opened or initially saved or ask for new one--is this new file entirelyor copy of the prior text with its known encoding under new namebecause of such ambiguitieswe allow the known-encoding memory feature to be disabled for save asor for both save and save as in the configuration module as shippedit is enabled for save onlynot save as in all casessave encoding prompt dialogs are prefilled with known encoding name as default the ordering of choice seems debatable in general for instanceperhaps save as should fall back on the known encoding if not asking the useras isif configured to not ask and not use known encodingthis operation will fall back on saving per an encoding in the configuration file or the platform default ( utf- )which may be less than ideal for email parts of known encodings and so on because such user interface choices require wider use to resolve wellthe general and partly heuristic policy here is to support every option for illustration purposes in this bookand rely on user configuration settings to resolve choices in practicethoughsuch wide flexibility may turn out to be overkillmost users probably just require one of the policies supported here it may also prove better to allow unicode policies to be selected in the gui itselfinstead of coded in configuration module for instanceperhaps every opensaveand save as should allow unicode encoding selectionwhich defaults to the last known encodingif any implementing this as pull-down encoding list or entry field in the save and open dialogs would avoid an extra pop up and achieve much the same flexibility in pyedit' current implementationenabling user prompts in the configuration file for both opens and saves will have much the same effectand at least based upon use cases 've encountered to datethat is probably the best policy to adopt for most contexts pyedita text editor program/object
5,262
open uses passed-in encodingif anyor else prompts for an encoding name first save reuses known encoding if it has oneand otherwise prompts for new file saves save as always prompts for an encoding name first for the new file grep allows an encoding to be input in its dialog to apply to the full tree searched on the other handbecause the platform default will probably work silently without extra gui complexity for the vast majority of users anyhowthe textconfig setting can prevent the pop ups altogether and fall back on an explicit encoding or platform default ultimatelystructuring encoding selection well requires the sort of broad user experience and feedback which is outside this book' scopenot the guesses of single developer as alwaysfeel free to tailor as you like see the test subdirectory in the examples for few unicode text files to experiment with opening and savingin conjunction with textconfig changes as suggested when we saw figures - and - this directory contains files that use international character setssaved in different encodings for instancefile email-part--koi - there is formatted per the russian encoding koi -rand email-part--koi - --utf is the same file saved in utf- encoding formatthe latter works well in notepad on windowsbut the former will only display properly when giving an explicit encoding name to pyedit better yetmake few unicode files yourselfby changing textconfig to hardcode encodings or always ask for encodings--thanks largely to python ' unicode supportpyedit allows you to save and load in whatever encoding you wish more on quit checksthe event revisited before we get to the codeone of version ' changes merits few additional wordsbecause it illustrates the fundamentals of tkinter window closure in realistic context we learned in that tkinter also has event for the bind method which is run when windows and widgets are destroyed although we could bind this event on pyedit windows or their text widgets to catch destroys on program exitthis won' quite help with the use case here scripts cannot generally do anything guirelated in this event' callbackbecause the gui is being torn down in particularboth testing text widget for modifications and fetching its content in handler can fail with an exception popping up save verification dialog at this point may act oddlytooit only shows up after some of the window' widgets may have already been erased (including the text widget whose contents the user may wish to inspect and save!)and it might sometimes refuse to go away altogether as also mentioned in running quit method call does not trigger any eventsbut does trigger fatal python error message on exit to use destroy events at allpyedit would have to be redesigned to close windows on quit requests with the destroy method onlyand rely on the tk root window destruction protocol for exitsimmediate shutdowns would be unsupportedor require tools such as complete gui programs
5,263
(pun nearly accidentalin other wordswon' help--it doesn' support the goal of verifying saves on window closesand it doesn' address the issue of quit and destroy calls run for widgets outside the scope of pyedit window classes because of such complicationspyedit instead relies on checking for changes in each individual window before closedand for changes in its cross-process window list before quits in any of its main windows applications that follow its expected window model check for changes automatically applications that embed pyedit as component of larger guior use it in other ways that are outside pyedit' controlare responsible for testing for edit changes on closes if they should be savedbefore the pyedit object or its widgets are destroyed to experiment with the event' behavior yourselfsee file destroyer py in the book examples packageit simulates what pyedit would need to do on here is the crucial subset of its codewith comments that explain behaviordef ondeleterequest()print('got wm delete'root destroy(def dorootdestroy(event)print('got event 'if event widget =textprint('for text'print(text edit_modified()ans askyesno('save stuff?''save?'if ansprint(text get(' 'end+'- ')on window xcan cancel destroy triggers called for each widget in root <tcl errorinvalid widget <may behave badly <tcl errorinvalid widget root tk(text text(rootundo= autoseparators= text pack(root bind(''dorootdestroyroot protocol('wm_delete_window'ondeleterequestfor root and children on window button button(roottext='destroy'command=root destroypack(button(roottext='quit'command=root quitpack(mainloop(triggers <fatal python errorno on quit(see the code listings in the next section for more on all of the above also be sure to see the mail file' documentation string for list of suggested enhancements and open issues (noted under "tbd"pyedit is largely designed to work according to my preferencesbut it' open to customization for yours pyedit source code the pyedit program consists of only small configuration module and one main source filewhich is just over , lines long-- py that can be either run or imported for pyedita text editor program/object
5,264
with an execfile('texteditor py'call the pyw suffix avoids the dos console streams window pop up when launched by clicking on windows todaypyw files can be both imported and runlike normal py files (they can also be double-clickedand launched by python tools such as os system and os startfile)so we don' really need separate file to support both import and console-less run modes retained the pythoughin order to see printed text during development and to use pyedit as simple ide--when the run code option is selectedin nonfile modeprinted output from code being edited shows up in pyedit' dos console window in windows clients will normally import the py file user configurations file on to the code firstpyedit' user configuration module is listed in example - this is mostly conveniencefor providing an initial look-and-feel other than the default pyedit is coded to work even if this module is missing or contains syntax errors this file is primarily intended for when pyedit is the top-level script run (in which case the file is imported from the current directory)but you can also define your own version of this file elsewhere on your module import search path to customize pyedit see texteditor py ahead for more on how this module' settings are loaded its contents are loaded by two different imports--one import for cosmetic settings assumes this module itself (not its packageis on the module search path and skips it if not foundand the other import for unicode settings always locates this file regardless of launch modes here' what this division of configuration labor means for clientsbecause the first import for cosmetic settings is relative to the module search pathnot to the main file' packagea new textconfig py can be defined in each client application' home directory to customize pyedit windows per client converselyunicode settings here are always loaded from this file using package relative imports if neededbecause they are more critical and unlikely to vary the package relative import used for this is equivalent to full package import from the pp rootbut not dependent upon directory structure like much of the heuristic unicode interface described earlierthis import model is somewhat preliminaryand may require revision if actual usage patterns warrant example - pp \gui\texteditor\textconfig py ""pyedit (texteditor pyuser startup configuration module""#general configurations comment-out any setting in this section to accept tk or program defaultscan also change font/colors from gui menusand resize window when openimported via search pathcan define per client appskipped if not on the path complete gui programs
5,265
font ('courier' 'normal'familysizestyle style'bold italicinitial color bg 'lightcyanfg 'blackdefault=whiteblack colorname or rgb hexstr 'powder blue''# initial size height width tk default lines tk default characters search case-insensitive caseinsens true default= /true (on# unicode encoding behavior and names for file opens and savesattempts the cases listed below in the order shownuntil the first one that worksset all variables to false/empty/ to use your platform' default (which is 'utf- on windowsor 'asciior 'latin- on others like unix)savesuseknownencoding =no =yes for save only =yes for save and saveasimported from this file alwayssys path if mainelse package relative#opensaskuser true opensencoding ' tries internally known type first ( email charset if truetry user input next (prefill with defaults if nonemptytry this encoding next'latin- ''cp tries sys getdefaultencoding(platform default next uses binary mode bytes and tk policy as the last resort savesuseknownencoding savesaskuser true savesencoding ' if try known encoding from last open or save if truetry user input next (prefill with known? if nonemptytry this encoding next'utf- 'etc tries sys getdefaultencoding(as last resort windows (and otherlaunch files nextexample - gives the pyw launching file used to suppress dos pop up on windows when run in some modes (for instancewhen double-clicked)but still allow for console when the py file is run directly (to see the output of edited code run in nonfile modefor exampleclicking this directly is similar to the behavior when pyedit is run from the pydemos or pygadgets demo launcher bars example - pp \gui\texteditor\texteditornoconsole pyw ""run without dos pop up on windowscould use just pyw for both imports and launchbut py file retained for seeing any printed text ""exec(open('texteditor py'read()as if pasted here (or texteditor main()pyedita text editor program/object
5,266
using notepad to view text files from command lines run in arbitrary places and wrote the script in example - to launch pyedit in more general and automated fashion this script disables the dos pop uplike example - when clicked or run via desktop shortcut on windowsbut also takes care to configure the module search path on machines where haven' used control panel to do soand allows for other launching scenarios where the current working directory may not be the same as the script' directory example - pp \gui\texteditor\pyedit pyw #!/usr/bin/python ""convenience script to launch pyedit from arbitrary places with the import path set as requiredsys path for imports and open(must be relative to the known top-level script' dirnot cwd -cwd is script' dir if run by shortcut or icon clickbut may be anything if run from command-line typed into shell console windowuse argv paththis is pyw to suppress console pop-up on windowsadd this script' dir to your system path to run from command-linesworks on unix tooand handled portably""import sysos mydir os path dirname(sys argv[ ]sys path insert( os sep join([mydir[']* )exec(open(os path join(mydir'texteditor py')read()use my dir for openpath importspp root up to run this from command line in console windowit simply has to be on your system path--the action taken by the first line in the following could be performed just once in control panel on windowsc:\pp \internet\webset path=%path%; :\pp \gui\texteditor :\pp \internet\webpyedit pyw test-cookies py this script works on unixtooand is unnecessary if you set your pythonpath and path system variables (you could then just run texteditor py directly)but don' do so on all the machines use for more funtry registering this script to open txtfiles automatically on your computer when their icons are clicked or their names are typed alone on command line (if you can bear to part with notepadthat ismain implementation file and finallythe module in example - is pyedit' implementation this file may run directly as top-level scriptor it can be imported from other applications its code is organized by the gui' main menu options the main classes used to start and embed pyedit object appear at the end of this file study this listing while you experiment with pyeditto learn about its features and techniques complete gui programs
5,267
""###############################################################################pyedit python/tkinter text file editor and component uses the tk text widgetplus guimaker menus and toolbar buttons to implement full-featured text editor that can be run as standalone programand attached as component to other guis also used by pymailgui and pyview to edit mail text and image file notesand by pymailgui and pydemos in pop-up mode to display source and text files new in version ( -updated to run under python ( -added "grepsearch menu option and dialogthreaded external files search -verify app exit on quit if changes in other edit windows in process -supports arbitrary unicode encodings for filesper textconfig py settings -update change and font dialog implementations to allow many to be open -runs self update(before setting text in new editor for loadfirst -various improvements to the run code optionper the next section run code improvements-use base name after chdir to run code filenot possibly relative path -use launch modes that support arguments for run code file mode on windows -run code inherits launchmodes backslash conversion (no longer requirednew in version ( -added simple font components input dialog -use tk undo stack api to add undo/redo text modifications -now verifies on quitopennewrunonly if text modified and unsaved -searches are case-insensitive now by default -configuration module for initial font/color/size/searchcase tbd (and suggested exercises)-could also allow search case choice in gui (not just config file-could use re patterns for searches and greps (see text -could experiment with syntax-directed text colorization (see idleothers-could try to verify app exit for quit(in non-managed windows too-could queue each result as found in grep dialog thread to avoid delay -could use images in toolbar buttons (per examples of this in -could scan line to map tk insert position column to account for tabs on info -could experiment with "greptbd unicode issues (see notes in the code)###############################################################################""version ' import sysos platformargsrun tools from tkinter import base widgetsconstants from tkinter filedialog import opensaveas standard dialogs from tkinter messagebox import showinfoshowerroraskyesno from tkinter simpledialog import askstringaskinteger from tkinter colorchooser import askcolor from pp gui tools guimaker import frame menu/toolbar builders general configurations trypyedita text editor program/object
5,268
configs textconfig __dict__ exceptconfigs {startup font and colors work if not on the path or bad define in client app directory helptext """pyedit version % april ( january ( october programming python th edition mark lutzfor 'reilly mediainc text editor program and embeddable object componentwritten in python/tkinter use menu tear-offs and toolbar for quick access to actionsand alt-key shortcuts for menus additions in version %ssupports python new "grepexternal files search dialog verifies app quit if other edit windows changed supports arbitrary unicode encodings for files allows multiple change and font dialogs various improvements to the run code option prior version additionsfont pick dialog unlimited undo/redo quit/open/new/run prompt save only if changed searches are case-insensitive startup configuration module textconfig py ""start ' sel_first sel firstsel_last sel lastindex of first charrow= ,col= map sel tag to index same as 'sel lastfontscale if sys platform[: !'win'fontscale use bigger font on linux and other non-windows boxes ###############################################################################main classimplements editor guiactions requires flavor of guimaker to be mixed in by more specific subclassesnot direct subclass of guimaker because that class takes multiple forms ###############################################################################class texteditorstartfiledir editwindows [mix with menu/toolbar frame class for dialogs for process-wide quit check unicode configurations imported in class to allow overrides in subclass or self complete gui programs
5,269
from textconfig import my dir is on the path opensaskuseropensencodingsavesuseknownencodingsavesaskusersavesencodingelsefrom textconfig import always from this package opensaskuseropensencodingsavesuseknownencodingsavesaskusersavesencodingftypes [('all files''*')('text files'txt')('python files'py')for file open dialog customize in subclass or set in each instance colors [{'fg':'black''bg':'white'}{'fg':'yellow''bg':'black'}{'fg':'white''bg':'blue'}{'fg':'black''bg':'beige'}{'fg':'yellow''bg':'purple'}{'fg':'black''bg':'brown'}{'fg':'lightgreen''bg':'darkgreen'}{'fg':'darkblue''bg':'orange'}{'fg':'orange''bg':'darkblue'}color pick list first item is default tailor me as desired or do pickbg/fg chooser fonts [('courier' +fontscale'normal')('courier' +fontscale'normal')('courier' +fontscale'bold')('courier' +fontscale'italic')('times' +fontscale'normal')('helvetica' +fontscale'normal')('ariel' +fontscale'normal')('system' +fontscale'normal')('courier' +fontscale'normal')platform-neutral fonts (familysizestyleor pop up listbox make bigger on linux use 'bold italicfor also 'underline'etc def __init__(selfloadfirst=''loadencode='')if not isinstance(selfguimaker)raise typeerror('texteditor needs guimaker mixin'self setfilename(noneself lastfind none self opendialog none self savedialog none self knownencoding none unicodetill open or save self text focus(else must click in text if loadfirstself update( else line see book self onopen(loadfirstloadencodedef start(self)run by guimaker __init__ self menubar configure menu/toolbar ('file' guimaker menu def tree [('open ' self onopen)build in method for self ('save' self onsave)labelshortcutcallback ('save as ' self onsaveas)('new' self onnew)'separator'('quit ' self onquit)pyedita text editor program/object
5,270
('edit' [('undo' self onundo)('redo' self onredo)'separator'('cut' self oncut)('copy' self oncopy)('paste' self onpaste)'separator'('delete' self ondelete)('select all' self onselectall))('search' [('goto ' self ongoto)('find ' self onfind)('refind' self onrefind)('change ' self onchange)('grep ' self ongrep))('tools' [('pick font ' self onpickfont)('font list' self onfontlist)'separator'('pick bg ' self onpickbg)('pick fg ' self onpickfg)('color list' self oncolorlist)'separator'('info ' self oninfo)('clone' self onclone)('run code' self onruncode))self toolbar ('save'self onsave{'side'left})('cut'self oncut{'side'left})('copy'self oncopy{'side'left})('paste'self onpaste{'side'left})('find'self onrefind{'side'left})('help'self help{'side'right})('quit'self onquit{'side'right})def makewidgets(self)name label(selfbg='black'fg='white'name pack(side=topfill=xvbar scrollbar(selfhbar scrollbar(selforient='horizontal'text text(selfpadx= wrap='none'text config(undo= autoseparators= run by guimaker __init__ add below menuabove tool menu/toolbars are packed guimaker frame packs itself vbar pack(side=rightfill=yhbar pack(side=bottomfill=xtext pack(side=topfill=bothexpand=yestext config(yscrollcommand=vbar settext config(xscrollcommand=hbar set complete gui programs disable line wrapping default is pack text last else sbars clipped call vbar set on text move
5,271
hbar config(command=text xviewcall text yview on scroll move or hbar['command']=text xview apply user configs or defaults startfont configs get('font'self fonts[ ]startbg configs get('bg'self colors[ ]['bg']startfg configs get('fg'self colors[ ]['fg']text config(font=startfontbg=startbgfg=startfgif 'heightin configstext config(height=configs['height']if 'widthin configstext config(width =configs['width']self text text self filelabel name ###########################################################################file menu commands ###########################################################################def my_askopenfilename(self)objects remember last result dir/file if not self opendialogself opendialog open(initialdir=self startfiledirfiletypes=self ftypesreturn self opendialog show(def my_asksaveasfilename(self)objects remember last result dir/file if not self savedialogself savedialog saveas(initialdir=self startfiledirfiletypes=self ftypesreturn self savedialog show(def onopen(selfloadfirst=''loadencode='')"" total rewrite for unicode supportopen in text mode with an encoding passed ininput from the userin textconfigor platform defaultor open as binary bytes for arbitrary unicode encodings as last resort and drop \ in windows end-lines if present so text displays normallycontent fetches are returned as strso need to encode on saveskeep encoding used heretests if file is okay ahead of time to try to avoid openswe could also load and manually decode bytes to str to avoid multiple open attemptsbut this is unlikely to try all casesencoding behavior is configurable in the local textconfig py tries known type first if passed in by client (email charsets if opensaskuser truetry user input next (prefill wih defaults if opensencoding nonemptytry this encoding next'latin- 'etc tries sys getdefaultencoding(platform default next uses binary mode bytes and tk policy as the last resort ""if self text_edit_modified() if not askyesno('pyedit''text has changeddiscard changes?')return pyedita text editor program/object
5,272
if not filereturn if not os path isfile(file)showerror('pyedit''could not open file filereturn try known encoding if passed and accurate ( emailtext none empty file 'falsetest for noneif loadencodetrytext open(file' 'encoding=loadencoderead(self knownencoding loadencode except (unicodeerrorlookuperrorioerror)lookupbad name pass try user inputprefill with next choice as default if text =none and self opensaskuserself update(else dialog doesn' appear in rare cases askuser askstring('pyedit''enter unicode encoding for open'initialvalue=(self opensencoding or sys getdefaultencoding(or '')if askusertrytext open(file' 'encoding=askuserread(self knownencoding askuser except (unicodeerrorlookuperrorioerror)pass try config file (or before ask user?if text =none and self opensencodingtrytext open(file' 'encoding=self opensencodingread(self knownencoding self opensencoding except (unicodeerrorlookuperrorioerror)pass try platform default (utf- on windowstry utf always?if text =nonetrytext open(file' 'encoding=sys getdefaultencoding()read(self knownencoding sys getdefaultencoding(except (unicodeerrorlookuperrorioerror)pass last resortuse binary bytes and rely on tk to decode if text =nonetrytext open(file'rb'read(bytes for unicode text text replace( '\ \ ' '\ 'for displaysaves self knownencoding none except ioerrorpass complete gui programs
5,273
showerror('pyedit''could not decode and open file fileelseself setalltext(textself setfilename(fileself text edit_reset( clear undo/redo stks self text edit_modified( clear modified flag def onsave(self)self onsaveas(self currfilemay be none def onsaveas(selfforcefile=none)"" total rewrite for unicode supporttext content is always returned as strso we must deal with encodings to save to file hereregardless of open mode of the output file (binary requires bytesand text must encode)tries the encoding used when opened or saved (if known)user inputconfig file settingand platform default lastmost users can use platform defaultretains successful encoding name here for next savebecause this may be the first save after new or manual text insertionsave and saveas may both use last known encodingper config file (it probably should be used for savebut saveas usage is unclear)gui prompts are prefilled with the known encoding if there is onedoes manual text encode(to avoid creating filetext mode files perform platform specific end-line conversionwindows \ dropped if present on open by text mode (autoand binary mode (manually)if manual content insertsmust delete \ else duplicates hereknownencoding=none before first open or saveafter newif binary openencoding behavior is configurable in the local textconfig py if savesuseknownencoding try encoding from last open or save if savesaskuser truetry user input next (prefill with known? if savesencoding nonemptytry this encoding next'utf- 'etc tries sys getdefaultencoding(as last resort ""filename forcefile or self my_asksaveasfilename(if not filenamereturn text self getalltext(encpick none str stringwith \ eolnseven if read/inserted as bytes try known encoding at latest open or saveif any if self knownencoding and (forcefile and self savesuseknownencoding > or (not forcefile and self savesuseknownencoding > ))trytext encode(self knownencodingencpick self knownencoding except unicodeerrorpass enc knownon saveon saveaspyedita text editor program/object
5,274
if not encpick and self savesaskuserself update(else dialog doesn' appear in rare cases askuser askstring('pyedit''enter unicode encoding for save'initialvalue=(self knownencoding or self savesencoding or sys getdefaultencoding(or '')if askusertrytext encode(askuserencpick askuser except (unicodeerrorlookuperror)lookuperrorbad name pass unicodeerrorcan' encode try config file if not encpick and self savesencodingtrytext encode(self savesencodingencpick self savesencoding except (unicodeerrorlookuperror)pass try platform default (utf on windowsif not encpicktrytext encode(sys getdefaultencoding()encpick sys getdefaultencoding(except (unicodeerrorlookuperror)pass open in text mode for endlines encoding if not encpickshowerror('pyedit''could not encode for file filenameelsetryfile open(filename' 'encoding=encpickfile write(textfile close(exceptshowerror('pyedit''could not write file filenameelseself setfilename(filenamemay be newly created self text edit_modified( clear modified flag self knownencoding encpick keep enc for next save don' clear undo/redo stksdef onnew(self)""start editing new file from scratch in current windowsee onclone to pop-up new independent edit window instead""if self text_edit_modified() if not askyesno('pyedit''text has changeddiscard changes?')return self setfilename(none complete gui programs
5,275
self text edit_reset(self text edit_modified( self knownencoding none clear undo/redo stks clear modified flag unicode type unknown def onquit(self)""on quit menu/toolbar select and wm border button in toplevel windows don' exit app if others changed don' ask if self unchangedmoved to the top-level window classes at the end since may vary per usagea quit in gui might quit(to exitdestroy(just one topleveltkor edit frameor not be provided at all when run as an attached componentcheck self for changesand if might quit()main windows should check other windows in the process-wide list to see if they have changed too""assert false'onquit must be defined in window-specific sublassdef text_edit_modified(self)"" this now worksseems to have been bool result type issue in tkinter self text edit_modified(broken in python do manually for now""return self text edit_modified(#return self tk call((self text _w'edit'('modified'none)###########################################################################edit menu commands ###########################################################################def onundo(self) trytk keeps undo/redo stacks self text edit_undo(exception if stacks empty except tclerrormenu tear-offs for quick undo showinfo('pyedit''nothing to undo'def onredo(self) redo an undone tryself text edit_redo(except tclerrorshowinfo('pyedit''nothing to redo'def oncopy(self)get text selected by mouseetc if not self text tag_ranges(sel)save in cross-app clipboard showerror('pyedit''no text selected'elsetext self text get(sel_firstsel_lastself clipboard_clear(self clipboard_append(textdef ondelete(self)delete selected textno save if not self text tag_ranges(sel)showerror('pyedit''no text selected'elseself text delete(sel_firstsel_lastpyedita text editor program/object
5,276
if not self text tag_ranges(sel)showerror('pyedit''no text selected'elseself oncopy(save and delete selected text self ondelete(def onpaste(self)trytext self selection_get(selection='clipboard'except tclerrorshowerror('pyedit''nothing to paste'return self text insert(inserttextadd at current insert cursor self text tag_remove(sel' 'endself text tag_add(selinsert+'-%dclen(text)insertself text see(insertselect itso it can be cut def onselectall(self)self text tag_add(sel' 'end+'- 'self text mark_set(insert' 'self text see(insertselect entire text move insert point to top scroll to top ###########################################################################search menu commands ###########################################################################def ongoto(selfforceline=none)line forceline or askinteger('pyedit''enter line number'self text update(self text focus(if line is not nonemaxindex self text index(end+'- 'maxline int(maxindex split(')[ ]if line and line <maxlineself text mark_set(insert'% linegoto line self text tag_remove(sel' 'enddelete selects self text tag_add(selinsert'insert 'select line self text see(insertscroll to line elseshowerror('pyedit''bad line number'def onfind(selflastkey=none)key lastkey or askstring('pyedit''enter search string'self text update(self text focus(self lastfind key if key nocase nocase configs get('caseinsens'true config where self text search(keyinsertendnocase=nocaseif not wheredon' wrap showerror('pyedit''string not found'else complete gui programs
5,277
self text tag_remove(sel' 'endself text tag_add(selwherepastkeyself text mark_set(insertpastkeyself text see(whereindex past key remove any sel select key for next find scroll display def onrefind(self)self onfind(self lastfinddef onchange(self)""non-modal find/change dialog pass per-dialog inputs to callbacksmay be change dialog open ""new toplevel(selfnew title('pyedit change'label(newtext='find text?'relief=ridgewidth= grid(row= column= label(newtext='change to?'relief=ridgewidth= grid(row= column= entry entry(newentry entry(newentry grid(row= column= sticky=ewentry grid(row= column= sticky=ewdef onfind()self onfind(entry get()use my entry in enclosing scope runs normal find dialog callback def onapply()self ondochange(entry get()entry get()button(newtext='find'command=onfind grid(row= column= sticky=ewbutton(newtext='apply'command=onapplygrid(row= column= sticky=ewnew columnconfigure( weight= expandable entries def ondochange(selffindtextchangeto)on apply in change dialogchange and refind if self text tag_ranges(sel)self text delete(sel_firstsel_lastself text insert(insertchangetoself text see(insertself onfind(findtextself text update(must find first deletes if empty goto next appear force refresh def ongrep(self)""new in version threaded external file searchsearch matched filenames in directory tree for stringlistbox clicks open matched file at line of occurrencesearch is threaded so the gui remains active and is not blockedand to allow multiple greps to overlap in timecould use threadtoolsbut avoid loop in no active grepgrep unicode policytext files content in the searched tree might be in any unicode encodingwe don' ask about each (as we do for opens)but allow the encoding used for the entire pyedita text editor program/object
5,278
text defaultand skip files that fail to decodein worst casesusers may need to run grep times if encodings might existelse opens may raise exceptionsand opening in binary mode might fail to match encoded text against search stringtbdbetter to issue an error if any file fails to decodebut utf- -bytes/char format created in notepad may decode without error per utf- and search strings won' be foundtbdcould allow input of multiple encoding namessplit on commatry each one for every filewithout open loadencode""from pp gui shellgui formrows import makeformrow nonmodal dialogget dirnnamefilenamepattgrepkey popup toplevel(popup title('pyedit grep'var makeformrow(popuplabel='directory root'width= browse=falsevar makeformrow(popuplabel='filename pattern'width= browse=falsevar makeformrow(popuplabel='search string'width= browse=falsevar makeformrow(popuplabel='content encoding'width= browse=falsevar set('current dir var set('py'initial values var set(sys getdefaultencoding()for file contentnot filenames cb lambdaself ondogrep(var get()var get()var get()var get()button(popuptext='go',command=cbpack(def ondogrep(selfdirnamefilenamepattgrepkeyencoding)""on go in grep dialogpopulate scrolled list with matches tbdshould producer thread be daemon so it dies with app""import threadingqueue make non-modal un-closeable dialog mypopup tk(mypopup title('pyedit grepping'status label(mypopuptext='grep thread searching for% grepkeystatus pack(padx= pady= mypopup protocol('wm_delete_window'lambdanoneignore close start producer threadconsumer loop myqueue queue queue(threadargs (filenamepattdirnamegrepkeyencodingmyqueuethreading thread(target=self grepthreadproducerargs=threadargsstart(self grepthreadconsumer(grepkeyencodingmyqueuemypopupdef grepthreadproducer(selffilenamepattdirnamegrepkeyencodingmyqueue)""in non-gui parallel threadqueue find find results listcould also queue matches as foundbut need to keep windowfile content and file names may both fail to decode heretbdcould pass encoded bytes to find(to avoid filename decoding excs in os walk/listdirbut which encoding to use complete gui programs
5,279
footnote issue fnmatch always converts bytes per latin- ""from pp tools find import find matches [tryfor filepath in find(pattern=filenamepattstartdir=dirname)trytextfile open(filepathencoding=encodingfor (linenumlinestrin enumerate(textfile)if grepkey in linestrmsg '% @% [% ](filepathlinenum linestrmatches append(msgexcept unicodeerror as xprint('unicode error in:'filepathxegdecodebom except ioerror as xprint('io error in:'filepathxegpermission finallymyqueue put(matchesstop consumer loop on find excsfilenamesdef grepthreadconsumer(selfgrepkeyencodingmyqueuemypopup)""in the main gui threadwatch queue for results or []there may be multiple active grep threads/loops/queuesthere may be other types of threads/checkers in processespecially when pyedit is attached component (pymailgui)""import queue trymatches myqueue get(block=falseexcept queue emptymyargs (grepkeyencodingmyqueuemypopupself after( self grepthreadconsumer*myargselsemypopup destroy(close status self update(erase it now if not matchesshowinfo('pyedit''grep found no matches for%rgrepkeyelseself grepmatcheslist(matchesgrepkeyencodingdef grepmatcheslist(selfmatchesgrepkeyencoding)""populate list after successful matcheswe already know unicode encoding from the searchuse it here when filename clickedso open doesn' ask user""from pp gui tour scrolledlist import scrolledlist print('matches for % % (grepkeylen(matches))catch list double-click class scrolledfilenames(scrolledlist)def runcommand(selfselection)fileline selection split(editor texteditormainpopup[' )[ split('@'pyedita text editor program/object
5,280
editor ongoto(int(line)editor text focus_force(noreally new non-modal widnow popup tk(popup title('pyedit grep matches% (% )(grepkeyencoding)scrolledfilenames(parent=popupoptions=matches###########################################################################tools menu commands ###########################################################################def onfontlist(self)self fonts append(self fonts[ ]del self fonts[ self text config(font=self fonts[ ]pick next font in list resizes the text area def oncolorlist(self)self colors append(self colors[ ]pick next color in list del self colors[ move current to end self text config(fg=self colors[ ]['fg']bg=self colors[ ]['bg']def onpickfg(self)self pickcolor('fg'added on def onpickbg(self)self pickcolor('bg'select arbitrary color in standard color dialog def pickcolor(selfpart)(triplehexstraskcolor(if hexstrself text config(**{parthexstr}this is too easy def oninfo(self)""pop-up dialog giving text statistics and cursor locationcaveat ( )tk insert position column counts tab as one charactertranslate to next multiple of to match visual""text self getalltext(added on in mins bytes len(textwords uses simple guesslines len(text split('\ ')any separated by whitespace words len(text split() xbytes is really chars index self text index(insertstr is unicode code points where tuple(index split(')showinfo('pyedit information''current location:\ \ 'line:\ % \ncolumn:\ % \ \nwhere 'file text statistics:\ \ 'chars:\ % \nlines:\ % \nwords:\ % \ (byteslineswords)def onclone(selfmakewindow=true)"" complete gui programs
5,281
inherits quit and other behavior of the window that it clones subclass must redefine/replace this if makes its own popupelse this creates bogus extra window here which will be empty""if not makewindownew none assume class makes its own window elsenew toplevel( new edit window in same process myclass self __class__ instance' (lowestclass object myclass(newattach/run instance of my class def onruncode(selfparallelmode=true)""run python code being edited--not an idebut handytries to run in file' dirnot cwd (may be pp root)inputs and adds command-line arguments for script filescode' stdin/out/err editor' start windowif anyrun with console window to see code' print outputsbut parallelmode uses start to open dos box for /omodule search path will include dir where startedin non-file modecode' tk root may be pyedit' windowsubprocess or multiprocessing modules may work here too fixed to use base file name after chdirnot path use startargs to allow args in file mode on windows run an update(after st dialog else nd dialog sometimes does not appear in rare cases""def askcmdargs()return askstring('pyedit''commandline arguments?'or 'from pp launchmodes import systemstartstartargsfork filemode false thefile str(self getfilename()if os path exists(thefile)filemode askyesno('pyedit''run from file?'self update( run update(if not filemoderun text string cmdargs askcmdargs(namespace {'__name__''__main__'run as top-level sys argv [thefilecmdargs split(could use threads exec(self getalltext('\ 'namespaceexceptions ignored elif self text_edit_modified() changed test showerror('pyedit''text changedyou must save before run'elsecmdargs askcmdargs(mycwd os getcwd(cwd may be root dirnamefilename os path split(thefileget dirbase os chdir(dirname or mycwdcd for filenames thecmd filename cmdargs not thefile if not parallelmoderun as file system(thecmdthecmd)(block editor elsepyedita text editor program/object
5,282
run startargs if cmdargs else start run(thecmdthecmd)(elsefork(thecmdthecmd)(os chdir(mycwdspawn in parallel support args or always spawn spawn in parallel go back to my dir def onpickfont(self)"" non-modal font spec dialog pass per-dialog inputs to callbackmay be font dialog open ""from pp gui shellgui formrows import makeformrow popup toplevel(selfpopup title('pyedit font'var makeformrow(popuplabel='family'browse=falsevar makeformrow(popuplabel='size'browse=falsevar makeformrow(popuplabel='style'browse=falsevar set('courier'var set(' 'suggested vals var set('bold italic'see pick list for valid inputs button(popuptext='apply'commandlambdaself ondofont(var get()var get()var get())pack(def ondofont(selffamilysizestyle)tryself text config(font=(familyint(size)style)exceptshowerror('pyedit''bad font specification'###########################################################################utilitiesuseful outside this class ###########################################################################def isempty(self)return not self getalltext(def getalltext(self)return self text get(' 'end+'- 'extract text as str string def setalltext(selftext)""callercall self update(first if just packedelse the initial position may be at line not line ( tk bug?""self text delete(' 'endstore text string in widget self text insert(endtextor ' 'text=bytes or str self text mark_set(insert' 'move insert point to top self text see(insertscroll to topinsert set def clearalltext(self)self text delete(' 'endclear text in widget def getfilename(self)return self currfile def setfilename(selfname) complete gui programs see alsoongoto(linenum
5,283
self filelabel config(text=str(name)def setknownencoding(selfencoding='utf- ') for saves if inserted self knownencoding encoding else saves use configaskdef setbg(selfcolor)self text config(bg=colordef setfg(selfcolor)self text config(fg=colordef setfont(selffont)self text config(font=fontdef setheight(selflines)self text config(height=linesdef setwidth(selfchars)self text config(width=charsdef clearmodified(self)self text edit_modified( def ismodified(self)return self text_edit_modified(to set manually from code 'black'hexstring ('family'size'style'default may also be from textcongif py clear modified flag changed since last resetdef help(self)showinfo('about pyedit'helptext ((version,)* )###############################################################################ready-to-use editor classes mixes in guimaker frame subclass which builds menu and toolbars these classes are common use casesbut other configurations are possiblecall texteditormain(mainloop(to start pyedit as standalone programredefine/extend onquit in subclass to catch exit or destroy (see pyview)caveatcould use windows py for iconsbut quit protocol is custom here ################################################################################ on quit()don' silently exit entire app if any other changed edit windows are open in the process changes would be lost because all other windows are closed tooincluding multiple tk editor parentsuses list to keep track of all pyedit window instances open in processthis may be too broad (if we destroy(instead of quit()need only check children of parent being destroyed)but better to err on side of being too inclusiveonquit moved here because varies per window type and is not present for allassumes texteditormainpopup is never parent to other editor windows toplevel children are destroyed with their parentsthis does not address closes outside the scope of pyedit classes here (tkinter quit is available on every widgetand any widget type may be toplevel parent!)client is responsible for checking for editor content changes in all uncovered casesnote that tkinter' bind event won' help herebecause its callback cannot run gui operations such as text change tests and fetches see the book and destroyer py for more details on this eventpyedita text editor program/object
5,284
when text editor owns the window ##################################class texteditormain(texteditorguimakerwindowmenu)""main pyedit windows that quit(to exit app on quit in guiand build menu on windowparent may be default tkexplicit tkor toplevelparent must be windowand probably should be tk so this isn' silently destroyed and closed with parentall main pyedit windows check all other pyedit windows open in the process for changes on quit in the guisince quit(here will exit the entire appthe editor' frame need not occupy entire window (may have other partssee pyview)but its quit ends programonquit is run for quit in toolbar or file menuas well as window border ""def __init__(selfparent=noneloadfirst=''loadencode='')editor fills whole parent window guimaker __init__(selfparentuse main window menus texteditor __init__(selfloadfirstloadencodeguimaker frame packs self self master title('pyedit versiontitlewm if standalone self master iconname('pyedit'self master protocol('wm_delete_window'self onquittexteditor editwindows append(selfdef onquit(self)on quit request in the gui close not self text_edit_modified(check selfask?check others if not closeclose askyesno('pyedit''text changedquit and discard changes?'if closewindows texteditor editwindows changed [ for in windows if !self and text_edit_modified()if not changedguimaker quit(selfquit ends entire app regardless of widget type elsenumchange len(changedverify '% other edit window% changedquit and discard anyhow?verify verify (numchange'sif numchange else ''if askyesno('pyedit'verify)guimaker quit(selfclass texteditormainpopup(texteditorguimakerwindowmenu)""popup pyedit windows that destroy(to close only self on quit in guiand build menu on windowmakes own toplevel parentwhich is child to default tk (for noneor other passed-in window or widget ( frame)adds to list so will be checked for changes if any pyedit main window quitsif any pyedit main windows will be createdparent of this should also be pyedit main window' parent so this is not closed silently while being trackedonquit is run for quit in toolbar or file menuas well as window border ""def __init__(selfparent=noneloadfirst=''wintitle=''loadencode='')create own window self popup toplevel(parent complete gui programs
5,285
use main window menus texteditor __init__(selfloadfirstloadencodea frame in new popup assert self master =self popup self popup title('pyedit version wintitleself popup iconname('pyedit'self popup protocol('wm_delete_window'self onquittexteditor editwindows append(selfdef onquit(self)close not self text_edit_modified(if not closeclose askyesno('pyedit''text changedquit and discard changes?'if closeself popup destroy(kill this window only texteditor editwindows remove(self(plus any child windowsdef onclone(self)texteditor onclone(selfmakewindow=falsei make my own pop-up ########################################when editor embedded in another window ########################################class texteditorcomponent(texteditorguimakerframemenu)""attached pyedit component frames with full menu/toolbar optionswhich run destroy(on quit in the gui to erase self onlya quit in the gui verifies if any changes in self (onlyheredoes not intercept window manager border xdoesn' own windowdoes not add self to changes tracking listpart of larger app""def __init__(selfparent=noneloadfirst=''loadencode='')use frame-based menus guimaker __init__(selfparentall menusbuttons on texteditor __init__(selfloadfirstloadencodeguimaker must init st def onquit(self)close not self text_edit_modified(if not closeclose askyesno('pyedit''text changedquit and discard changes?'if closeself destroy(erase self frame but do not quit enclosing app class texteditorcomponentminimal(texteditorguimakerframemenu)""attached pyedit component frames without quit and file menu optionson startupremoves quit from toolbarand either deletes file menu or disables all its items (possibly hackishbut sufficient)menu and toolbar structures are per-instance datachanges do not impact othersquit in gui never occursbecause it is removed from available options""def __init__(selfparent=noneloadfirst=''deletefile=trueloadencode='')self deletefile deletefile guimaker __init__(selfparentguimaker frame packs self pyedita text editor program/object
5,286
def start(self)texteditor start(selffor in range(len(self toolbar))if self toolbar[ ][ ='quit'del self toolbar[ibreak if self deletefilefor in range(len(self menubar))if self menubar[ ][ ='file'del self menubar[ibreak elsefor (namekeyitemsin self menubarif name ='file'items append([ , , , , ]guimaker start call delete quit in toolbar delete file menu itemsor just disable file ###############################################################################standalone program run ###############################################################################def testpopup()see pyview and pymail for component tests root tk(texteditormainpopup(roottexteditormainpopup(rootbutton(roottext='more'command=texteditormainpopuppack(fill=xbutton(roottext='quit'command=root quitpack(fill=xroot mainloop(def main()may be typed or clicked tryor associated on windows fname sys argv[ arg optional filename except indexerrorbuild in default tk root fname none texteditormain(loadfirst=fnamepack(expand=yesfill=bothpack optional mainloop(if __name__ ='__main__'#testpopup(main(when run as script run pyw for no dos box pyphotoan image viewer and resizer in we wrote simple thumbnail image viewer that scrolled its thumbnails in canvas that program in turn built on techniques and code we developed at the end of to handle images in both placesi promised that we' eventually meet more full-featured extension of the ideas we deployed in this sectionwe finally wrap up the thumbnail images thread by studying pyphoto-an enhanced image viewing and resizing program pyphoto' basic operation is complete gui programs
5,287
scrollable canvas when thumbnail is selectedthe corresponding image is displayed full size in pop-up window unlike our prior viewersthoughpyphoto is clever enough to scroll (rather than cropimages too large for the physical display moreoverpyphoto introduces the notion of image resizing--it supports mouse and keyboard events that resize the image to one of the display' dimensions and zoom the image in and out once images are openedthe resizing logic allows images to be grown or shrunk arbitrarilywhich is especially handy for images produced by digital camera that may be too large to view all at once as added touchespyphoto also allows the image to be saved in file (possibly after being resized)and it allows image directories to be selected and opened in the gui itselfinstead of just as command-line arguments put togetherpyphoto' features make it an image-processing programalbeit one with currently small set of processing tools encourage you to experiment with adding new features of your ownonce you get the hang of the python imaging library (pilapithe object-oriented nature of pyphoto makes adding new tools remarkably simple running pyphoto in order to run pyphotoyou'll need to fetch and install the pil extension package described in pyphoto inherits much of its functionality from pil--pil is used to support extra image types beyond those handled by standard tkinter ( jpeg imagesand to perform image-processing operations such as resizesthumbnail creationand saves pil is open source like pythonbut it is not presently part of the python standard library search the web for pil' location (currently safe betalso check the extensions directory of the examples distribution package for pil self-installer the best way to get feel for pyphoto is to run it live on your own machine to see how images are scrolled and resized herewe'll present few screenshots to give the general flavor of the interaction you can start pyphoto by clicking its iconor you can start it from the command line when run directlyit opens the images subdirectory in its source directorywhich contains handful of photos when you run it from the command lineyou can pass in an initial image directory name as command-line argument figure - captures the main thumbnail window when run directly internallypyphoto is loading or creating thumbnail images before this window appearsusing tools coded in startup may take few seconds the first time you open directorybut it is quick thereafter--pyphoto caches thumbnails in local subdirectory so that it can skip the generation step the next time the directory is opened technicallythere are three different ways pyphoto may start upviewing an explicit directory listed on the command lineviewing the default images directory when no command-line argument is given and when images is present where the program is runpyphotoan image viewer and resizer
5,288
or displaying simple one-button window that allows you to select directories to open on demandwhen no initial directory is given or present (see the code' __main__ logicpyphoto also lets you open additional folders in new thumbnail windowsby pressing the key on your keyboard in either thumbnail or an image window figure - for instancecaptures the pop-up window produced in windows to select new image folderand figure - shows the result when select directory copied from one of my digital camera cards--this is second pyphoto thumbnail window on the display figure - is also opened by the one-button window if no initial directory is available when thumbnail is selectedthe image is displayed in canvasin new pop-up window if it' too large for the displayyou can scroll through its full size with the window' scroll bars figure - captures one image after its thumbnail is clickedand figure - shows the save as dialog issued when the key is pressed in the image windowbe sure to type the desired filename extension ( jpgin this save as dialogbecause pil uses it to know how to save the image to the file in generalany number of pyphoto thumbnail and image windows can be open at onceand each image can be saved independently beyond the screenshots already shownthis system' interaction is difficult to capture in static medium such as this book--you're better off test-driving the program live complete gui programs
5,289
for exampleclicking the left and right mouse buttons will resize the image to the display' height and width dimensionsrespectivelyand pressing the and keys will zoom the image in and out in percent increments both resizing schemes allow you to shrink an image too large to see all at onceas well as expand small photos they also preserve the original aspect ratio of the photoby changing its height and width proportionallywhile blindly resizing to the display' dimensions would not (height or width may be stretchedonce resizedimages may be saved in files at their current size pyphoto is also smart enough to make windows full size on windowsif an image is larger than the display pyphoto source code because pyphoto simply extends and reuses techniques and code we met earlier in the bookwe'll omit detailed discussion of its code here for backgroundsee the discussion of image processing and pil in and the coverage of the canvas widget in in shortpyphoto uses canvases in two waysfor thumbnail collections and for opened images for thumbnailsthe same sort of canvas layout code as the earlier thumbnails viewer in example - is employed for imagesa canvas is used as wellbut the pyphotoan image viewer and resizer
5,290
canvas' scrollable (fullsize is the image sizeand the viewable area size is the minimum of the physical screen size or the size of the image itself the physical screen size is available from the maxsize(method of toplevel windows the net effect is that selected images may be scrolled nowtoowhich comes in handy if they are too big for your display ( common case for pictures snapped with newer digital camerasin additionpyphoto binds keyboard and mouse events to implement resizing and zoom operations with pilthis is simple--we save the original pil imagerun its resize method with the new image sizeand redraw the image in the canvas pyphoto also makes use of file open and save dialog objectsto remember the last directory visited pil supports additional operationswhich we could add as new eventsbut resizing is sufficient for viewer pyphoto does not currently use threadsto avoid becoming blocked for long-running tasks (opening large directory the first timefor instancesuch enhancements are left as suggested exercises complete gui programs
5,291
pyphoto is implemented as the single file of example - though it gets some utility for free by reusing the thumbnail generation function of the viewer_thumbs module that we originally wrote near the end of in example - to spare you from having to flip back and forth too muchhere' copy of the code of the thumbs function imported and used hereimported from def makethumbs(imgdirsize=( )subdir='thumbs')returns list of (image filenamethumb image object)thumbdir os path join(imgdirsubdirif not os path exists(thumbdir)os mkdir(thumbdirthumbs [for imgfile in os listdir(imgdir)thumbpath os path join(thumbdirimgfileif os path exists(thumbpath)thumbobj image open(thumbpaththumbs append((imgfilethumbobj)elseprint('making'thumbpathimgpath os path join(imgdirimgfiletryuse already created pyphotoan image viewer and resizer
5,292
imgobj image open(imgpathmake new thumb imgobj thumbnail(sizeimage antialiasbest downsize filter imgobj save(thumbpathtype via ext or passed thumbs append((imgfileimgobj)exceptnot always ioerror print("skipping"imgpathreturn thumbs some of this example' thumbnail selection window code is also very similar to our earlier limited scrolled-thumbnails example in but it is repeated in this file instead of importedto allow for future evolution (' functional subset is now officially demoted to prototypeas you study this filepay particular attention to the way it factors code into reused functions and methodsto avoid redundancyif we ever need to change the way zooming worksfor examplewe have just one method to changenot two also notice its scrolledcanvas class-- reusable component that handles the work of linking scroll bars and canvases complete gui programs
5,293
""###########################################################################pyphoto thumbnail image viewer with resizing and saves supports multiple image directory thumb windows the initial img dir is passed in as cmd arguses "imagesdefaultor is selected via main window buttonlater directories are opened by pressing "din image view or thumbnail windows viewer also scrolls popped-up images that are too large for the screenstill to do( rearrange thumbnails when window resizedbased on current window size( [doneoption to resize images to fit current window size( avoid scrolls if image size is less than window max sizeuse label if imgwide <scrwide and imghigh <scrhighnew in updated to run in python and latest pilnew in now does form of ( aboveimage is resized to one of the display' dimensions if clickedand zoomed in or out in increments on key pressesgeneralize mecaveatseems to lose qualitypixels after many resizes (this is probably limitation of pilthe following scaler adapted from pil' thumbnail code is similar to the screen height scaler herebut only shrinksxy imgwideimghigh if scrwidey max( scrwide / ) scrwide if scrhighx max( scrhigh / ) scrhigh ###########################################################################""import sysmathos from tkinter import from tkinter filedialog import saveasdirectory from pil import image from pil imagetk import photoimage from viewer_thumbs import makethumbs pil imagealso in tkinter pil photo widget replacement developed earlier in book remember last dirs across all windows savedialog saveas(title='save as (filename gives image type)'opendialog directory(title='select image directory to open'trace print or lambda *xnone appname 'pyphoto class scrolledcanvas(canvas)"" canvas in container that automatically makes vertical and horizontal scroll bars for itself ""def __init__(selfcontainer)canvas __init__(selfcontainerself config(borderwidth= pyphotoan image viewer and resizer
5,294
hbar scrollbar(containerorient='horizontal'vbar pack(side=rightfill=yhbar pack(side=bottomfill=xself pack(side=topfill=bothexpand=yespack canvas after bars so clipped first vbar config(command=self yviewhbar config(command=self xviewself config(yscrollcommand=vbar setself config(xscrollcommand=hbar setcall on scroll move call on canvas move class viewone(toplevel)""open single image in pop-up window when createda class because photoimage obj must be savedelse erased if reclaimedscroll if too big for displayon mouse clicksresizes to window' height or widthstretches or shrinkson / keypresszooms in/outboth resizing schemes maintain original aspect ratiocode is factored to avoid redundancy here as possible""def __init__(selfimgdirimgfileforcesize=())toplevel __init__(selfhelptxt '(click / or press / to resizes to saved to open)self title(appname imgfile helptxtimgpath os path join(imgdirimgfileimgpil image open(imgpathself canvas scrolledcanvas(selfself drawimage(imgpilforcesizeself canvas bind(''self onsizetodisplayheightself canvas bind(''self onsizetodisplaywidthself bind(''self onzoominself bind(''self onzoomoutself bind(''self onsaveimageself bind(''ondirectoryopenself focus(def drawimage(selfimgpilforcesize=())imgtk photoimage(image=imgpilscrwidescrhigh forcesize or self maxsize(imgwide imgtk width(imghigh imgtk height(fullsize ( imgwideimghighviewwide min(imgwidescrwideviewhigh min(imghighscrhighnot file=imgpath wm screen size , size in pixels same as imgpil size scrollable viewable canvas self canvas canvas delete('all'clear prior photo canvas config(height=viewhighwidth=viewwideviewable window size canvas config(scrollregion=fullsizescrollable area size canvas create_image( image=imgtkanchor=nw complete gui programs
5,295
self state('normal'elif sys platform[: ='win'self state('zoomed'self saveimage imgpil self savephoto imgtk trace((scrwidescrhigh)imgpil sizetoo big for displaynowin size per img do windows fullscreen others use geometry(keep reference on me def sizetodisplayside(selfscaler)resize to fill one side of the display imgpil self saveimage scrwidescrhigh self maxsize(wm screen size , imgwideimghigh imgpil size img size in pixels newwidenewhigh scaler(scrwidescrhighimgwideimghighif (newwide newhigh imgwide imghigh)filter image antialias shrinkantialias elsegrowbicub sharper filter image bicubic imgnew imgpil resize((newwidenewhigh)filterself drawimage(imgnewdef onsizetodisplayheight(selfevent)def scalehigh(scrwidescrhighimgwideimghigh)newhigh scrhigh newwide int(scrhigh (imgwide imghigh)return (newwidenewhighself sizetodisplayside(scalehighdef onsizetodisplaywidth(selfevent)def scalewide(scrwidescrhighimgwideimghigh)newwide scrwide newhigh int(scrwide (imghigh imgwide)return (newwidenewhighself sizetodisplayside(scalewide true div proportional true div def zoom(selffactor)zoom in or out in increments imgpil self saveimage widehigh imgpil size if factor antialias best if shrink filter image antialias also nearestbilinear elsefilter image bicubic new imgpil resize((int(wide factor)int(high factor))filterself drawimage(newdef onzoomin(selfeventincr )self zoom( incrdef onzoomout(selfeventdecr )self zoom( decrdef onsaveimage(selfevent)save current image state to file filename savedialog show(pyphotoan image viewer and resizer
5,296
self saveimage save(filenamedef ondirectoryopen(event)""open new image directory in new pop up available in both thumb and img windows ""dirname opendialog show(if dirnameviewthumbs(dirnamekind=topleveldef viewthumbs(imgdirkind=toplevelnumcols=noneheight= width= )""make main or pop-up thumbnail buttons windowuses fixed-size buttonsscrollable canvassets scrollable (fullsizeand places thumbs at abs , coordinates in canvasno longer assumes all thumbs are same sizegets max of all ( , )some may be smaller""win kind(helptxt '(press to open other)win title(appname imgdir helptxtquit button(wintext='quit'command=win quitbg='beige'quit pack(side=bottomfill=xcanvas scrolledcanvas(wincanvas config(height=heightwidth=widthinit viewable window size changes if user resizes thumbs makethumbs(imgdir[(imgfileimgobj)numthumbs len(thumbsif not numcolsnumcols int(math ceil(math sqrt(numthumbs))fixed or numrows int(math ceil(numthumbs numcols) true div max |hthumb=(nameobj)thumb size=(widthheightlinksize max(max(thumb[ sizefor thumb in thumbstrace(linksizefullsize ( upper left , (linksize numcols)(linksize numrowslower right , canvas config(scrollregion=fullsizescrollable area size rowpos savephotos [while thumbsthumbsrowthumbs thumbs[:numcols]thumbs[numcols:colpos for (imgfileimgobjin thumbsrowphoto photoimage(imgobjlink button(canvasimage=photodef handler(savefile=imgfile)viewone(imgdirsavefilelink config(command=handlerwidth=linksizeheight=linksize complete gui programs
5,297
canvas create_window(colposrowposanchor=nwwindow=linkwidth=linksizeheight=linksizecolpos +linksize savephotos append(photorowpos +linksize win bind(''ondirectoryopenwin savephotos savephotos return win if __name__ ='__main__'""open dir default or cmdline arg else show simple window to select ""imgdir 'imagesif len(sys argv imgdir sys argv[ if os path exists(imgdir)mainwin viewthumbs(imgdirkind=tkelsemainwin tk(mainwin title(appname 'open'handler lambdaondirectoryopen(nonebutton(mainwintext='open image directory'command=handlerpack(mainwin mainloop(pyviewan image and notes slideshow picture may be worth thousand wordsbut it takes considerably fewer to display one with python the next programpyviewimplements simple photo slideshow program in portable python/tkinter code it doesn' have any image-processing abilities such as pyphoto' resizingbut it does provide different toolssuch as image note filesand it can be run without the optional pil extension running pyview pyview pulls together many of the topics we studied in it uses after events to sequence slideshowdisplays image objects in an automatically sized canvasand so on its main window displays photo on canvasusers can either open and view photo directly or start slideshow mode that picks and displays random photo from directory at regular intervals specified with scale widget by defaultpyview slideshows show images in the book' image file directory (though the open button allows you to load images in arbitrary directoriesto view other sets of photoseither pass directory name in as first command-line argument or change the default directory name in the script itself can' show you slideshow in action herebut can show you the main window in general figure - shows the main pyviewan image and notes slideshow
5,298
pyview window' default display on windows created by running the slideshowplus py script we'll see in example - ahead though it' not obvious as rendered in this bookthe black-on-red label at the top gives the pathname of the photo file displayed for good timemove the slider at the bottom all the way over to " to specify no delay between photo changesand then click start to begin very fast slideshow if your computer is at least as fast as minephotos flip by much too fast to be useful for anything but subliminal advertising slideshow photos are loaded on startup to retain references to them (rememberyou must hold on to image objectsbut the speed with which large gifs can be thrown up in window in python is impressiveif not downright exhilarating the gui' start button changes to stop button during slideshow (its text attribute is reset with the widget config methodfigure - shows the scene after pressing stop at an opportune moment in additioneach photo can have an associated "notestext file that is automatically opened along with the image you can use this feature to record basic information about the photo press the note button to open an additional set of widgets that let you view complete gui programs
5,299
and change the note file associated with the currently displayed photo this additional set of widgets should look familiar--the pyedit text editor from earlier in this is attached to pyview in variety of selectable modes to serve as display and editing widget for photo notes figure - shows pyview with the attached pyedit noteediting component opened ( resized the window bit interactively for presentation hereembedding pyedit in pyview this makes for very big windowusually best viewed maximized (taking up the entire screenthe main thing to noticethoughis the lower-right corner of this displayabove the scale--it' simply an attached pyedit objectrunning the very same code listed in the earlier section because pyedit is implemented as gui classit can be reused like this in any gui that needs text-editing interface when embedded this waypyedit is nested frame attached to slideshow frame its menus are based on frame (it doesn' own the window at large)text content is stored and fetched directly by the enclosing programand some standalone options are pyviewan image and notes slideshow