O'Reilly logo

Python Programming On Win32 by Mark Hammond, Andy Robinson

Stay ahead with the world's most comprehensive technology and business learning platform.

With Safari, you learn the way you learn best. Get unlimited access to videos, live online training, learning paths, books, tutorials, and more.

Start Free Trial

No credit card required

Enhancing the Document

As mentioned previously, this ScribbleDocument object is responsible only for working with the document data, not for interacting with the user. This makes the ScribbleDocument quite simple. The first step is to add some public methods for working with the strokes. These functions look like:

class ScribbleDocument(pywin.mfc.docview.Document):
...
    def AddStroke(self, start, end, fromView):
        self.strokes.append((start, end))
        self.SetModifiedFlag()
        self.UpdateAllViews( fromView, None )
        
    def GetStrokes(self):
        return self.strokes

The first function appends the new stroke to the list of strokes. It also sets the document’s “modified flag.” This flag is used by MFC to automatically prompt the user to save the document as the program exits. It also automatically enables the File/Save option for the document.

The last thing the document must do is to load and save the data from a file. MFC itself handles displaying of the Save As, etc., dialogs, and calls Document functions to perform the actual save. The function names are OnOpenDocument() and OnSaveDocument() respectively.

As the strokes are a simple list, you can use the Python pickle module. The functions become quite easy:

def OnOpenDocument(self, filename): file = open(filename, "rb") self.strokes = pickle.load(file) file.close() win32ui.AddToRecentFileList(filename) return 1 def OnSaveDocument(self, filename): file = open(filename, "wb") pickle.dump(self.strokes, file) file.close() self.SetModifiedFlag(0) win32ui.AddToRecentFileList(filename) ...

With Safari, you learn the way you learn best. Get unlimited access to videos, live online training, learning paths, books, interactive tutorials, and more.

Start Free Trial

No credit card required