[Tutor] How to save and later open text from a wxTextCtrl widget to a text file?

John Fouhy john at fouhy.net
Tue Oct 17 02:56:43 CEST 2006


On 17/10/06, Pine Marten <pine508 at hotmail.com> wrote:
> I want to make a GUI in which user can write text in a text box and then
> click a button to save it to a text file.  I'm using wxPython's TextCtrl
> widget.
>
> Then later I would want the user to be able to open it back into that
> window.
>
> Any help appreciated, thank you.

Suppose you've got a TextCtrl:

myTextBox = wx.TextCtrl(parent, style=wx.TE_MULTILINE)

You can save it simply like this:

def save(event):
    savefile = open(self.filename, 'w')
    savefile.write(myTextBox.GetValue())
    savefile.close()
saveButton = wx.Button(parent, id=wx.ID_SAVE)
saveButton.Bind(wx.EVT_BUTTON, save)

Of course, you'll need some way of setting self.filename.  The usual
way would be to have a Save button and a Save as.. button, and have
Save as.. invoke a wx.FileDialog.

Something like:

def saveas(event):
    dialog = wx.FileDialog(parent, message='Choose a file',
style=wx.SAVE|wx.OVERWRITE_PROMPT)
    if dialog.ShowModal() == wx.ID_OK:
        self.savefile = dialog.GetFilename()
        save(event)
saveAsButton = wx.Button(parent, id=wx.ID_SAVEAS)
saveAsButton.Bind(wx.EVT_BUTTON, saveas)

You could also modify save() to automatically call saveas() if
self.filename is not set.
(just be careful of recursion if the user clicks cancel!)

Loading is the same except in the opposite direction.  Look at
wx.TextCtrl.SetValue and the style options for wx.FileDialog.

HTH!

-- 
John.


More information about the Tutor mailing list