| |||||||||||
| |||||||||||
wxPython text editor with open, save, etc
this example from a Well House Consultants training course
Source code: wx03_02.py Module: Y207
# Get the GUI stuff import wx # We're going to be handling files and directories import os # Set up some button numbers for the menu ID_ABOUT=101 ID_OPEN=102 ID_SAVE=103 ID_BUTTON1=300 ID_EXIT=200 class MainWindow(wx.Frame): def __init__(self,parent,title): # based on a frame, so set up the frame wx.Frame.__init__(self,parent,wx.ID_ANY, title) # Add a text editor and a status bar # Each of these is within the current instance # so that we can refer to them later. self.control = wx.TextCtrl(self, 1, style=wx.TE_MULTILINE) self.CreateStatusBar() # A Statusbar in the bottom of the window # Setting up the menu. filemenu is a local variable at this stage. filemenu= wx.Menu() # use ID_ for future easy reference - much better that "48", "404" etc # The & character indicates the short cut key filemenu.Append(ID_OPEN, "&Open"," Open a file to edit") filemenu.AppendSeparator() filemenu.Append(ID_SAVE, "&Save"," Save file") filemenu.AppendSeparator() filemenu.Append(ID_ABOUT, "&About"," Information about this program") filemenu.AppendSeparator() filemenu.Append(ID_EXIT,"E&xit"," Terminate the program") # Creating the menubar. menuBar = wx.MenuBar() menuBar.Append(filemenu,"&File") # Adding the "filemenu" to the MenuBar self.SetMenuBar(menuBar) # Adding the MenuBar to the Frame content. # Note - previous line stores the whole of the menu into the current object # Define the code to be run when a menu option is selected wx.EVT_MENU(self, ID_ABOUT, self.OnAbout) wx.EVT_MENU(self, ID_EXIT, self.OnExit) wx.EVT_MENU(self, ID_OPEN, self.OnOpen) wx.EVT_MENU(self, ID_SAVE, self.OnSave); # just "pass" in our demo # Set up a series of buttons arranged horizontally self.sizer2 = wx.BoxSizer(wx.HORIZONTAL) self.buttons=[] # Note - give the buttons numbers 1 to 6, generating events 301 to 306 # because IB_BUTTON1 is 300 for i in range(6): # describe a button bid = i+1 self.buttons.append(wx.Button(self, ID_BUTTON1+i, "Button &"+str(bid))) # add that button to the sizer2 geometry self.sizer2.Add(self.buttons[i],1,wx.EXPAND) # Set up the overall frame verically - text edit window above buttons # We want to arrange the buttons vertically below the text edit window self.sizer=wx.BoxSizer(wx.VERTICAL) self.sizer.Add(self.control,1,wx.EXPAND) self.sizer.Add(self.sizer2,0,wx.EXPAND) # Tell it which sizer is to be used for main frame # It may lay out automatically and be altered to fit window self.SetSizer(self.sizer) self.SetAutoLayout(1) self.sizer.Fit(self) # Show it !!! self.Show(1) # Define widgets early even if they're not going to be seen # so that they can come up FAST when someone clicks for them! self.aboutme = wx.MessageDialog( self, " A sample editor \n" " in wxPython","About Sample Editor", wx.OK) self.doiexit = wx.MessageDialog( self, " Exit - R U Sure? \n", "GOING away ...", wx.YES_NO) # dirname is an APPLICATION variable that we're choosing to store # in with the frame - it's the parent directory for any file we # choose to edit in this frame self.dirname = '' def OnAbout(self,e): # A modal show will lock out the other windows until it has # been dealt with. Very useful in some programming tasks to # ensure that things happen in an order that the programmer # expects, but can be very frustrating to the user if it is # used to excess! self.aboutme.ShowModal() # Shows it # widget / frame defined earlier so it can come up fast when needed def OnExit(self,e): # A modal with an "are you sure" check - we don't want to exit # unless the user confirms the selection in this case ;-) igot = self.doiexit.ShowModal() # Shows it if igot == wx.ID_YES: self.Close(True) # Closes out this simple application def OnOpen(self,e): # In this case, the dialog is created within the method because # the directory name, etc, may be changed during the running of the # application. In theory, you could create one earlier, store it in # your frame object and change it when it was called to reflect # current parameters / values dlg = wx.FileDialog(self, "Choose a file", self.dirname, "", "*.*", wx.OPEN) if dlg.ShowModal() == wx.ID_OK: self.filename=dlg.GetFilename() self.dirname=dlg.GetDirectory() # Open the file, read the contents and set them into # the text edit window filehandle=open(os.path.join(self.dirname, self.filename),'r') self.control.SetValue(filehandle.read()) filehandle.close() # Report on name of latest file read self.SetTitle("Editing ... "+self.filename) # Later - could be enhanced to include a "changed" flag whenever # the text is actually changed, could also be altered on "save" ... dlg.Destroy() def OnSave(self,e): # Save away the edited text # Open the file, do an RU sure check for an overwrite! dlg = wx.FileDialog(self, "Choose a file", self.dirname, "", "*.*", \ wx.SAVE | wx.OVERWRITE_PROMPT) if dlg.ShowModal() == wx.ID_OK: # Grab the content to be saved itcontains = self.control.GetValue() # Open the file for write, write, close self.filename=dlg.GetFilename() self.dirname=dlg.GetDirectory() filehandle=open(os.path.join(self.dirname, self.filename),'w') filehandle.write(itcontains) filehandle.close() # Get rid of the dialog to keep things tidy dlg.Destroy() # Set up a window based app, and create a main window in it app = wx.PySimpleApp() view = MainWindow(None, "Sample editor") # Enter event loop app.MainLoop() Learn about this subject
This module and example are covered as required on private courses.
Should you wish to cover this example and associated subjects, and you're attending a public course
to cover other topics with us, please see our extra topic program.
Books covering this topic
Yes. We have over 700 books in our library. Books
covering Python are listed here and when you've selected a
relevant book we'll link you on to Amazon to order.
Other Examples
This example comes from our "this" training module. You'll find a description of the topic and some
other closely related examples on the "this" module index page.
Full description of the source code
You can learn more about this example on the training courses listed on this page,
on which you'll be given a full set of training notes.
Many other training modules are available for download (for limited use) from our download centre under an Open Training Notes License. Other resources
• Our Solutions centre provides a number of longer technical articles.
• Our Opentalk forum archive provides a question and answer centre. • The Horse's mouth provides a daily tip or thought. • Further resources are available via the resources centre. • All of these resources can be searched through through our search engine • And there's a global index here. Purpose of this website
This is a sample program, class demonstration or answer from a
training course. It's main purpose
is to provide an after-course service to customers who have attended our
public private or
on site courses, but the examples are made
generally available under conditions described below.
Web site author
Conditions of use
Past attendees on our training courses are welcome to use individual
examples in the course of their programming, but must check
the examples they use to ensure that they are suitable for their
job. Remember that some of our examples show you how not to do
things - check in your notes. Well House Consultants take no responsibility
for the suitability of these example programs to customer's needs.
This program is copyright Well House Consultants Ltd. You are forbidden from using it for running your own training courses without our prior written permission. See our page on courseware provision for more details. Any of our images within this code may NOT be reused on a public URL without our prior permission. For Bona Fide personal use, we will often grant you permission provided that you provide a link back. Commercial use on a website will incur a license fee for each image used - details on request. |
| ||||||||||
PH: 01144 1225 708225 • EMAIL: info@wellho.net • WEB: http://www.wellho.net • SKYPE: wellho PAGE: http://www.wellho.net/resources/ex.php • PAGE BUILT: Sun Oct 11 14:50:09 2020 • BUILD SYSTEM: JelliaJamb |