adding "Print" menu in wxPython
rantingrick
rantingrick at gmail.com
Wed Jan 26 01:54:47 EST 2011
On Jan 26, 12:19 am, rantingrick <rantingr... at gmail.com> wrote:
Actually i found more cruft. Here is something that would be
acceptable although i had to wrap lines shorter than i normally would
for the sake of Usenet. Who ever wrote that code should be lashed 50
times! You still need some error handling for the open and save file
methods but crikey i can't do everything ;-)
#--STARTCODE--#
import wx
import os.path, sys
class MainWindow(wx.Frame):
def __init__(self, filename='noname.txt'):
wx.Frame.__init__(self, None, size=(400,200))
self.filename = filename
self.dirname = '.'
self.control = wx.TextCtrl(self, style=wx.TE_MULTILINE)
self.CreateMenu()
self.CreateStatusBar()
self.SetTitle('Editor %s'%self.filename)
self.dlgdefaults = {
'message':'Choose a file',
'defaultDir':self.dirname,
'wildcard':'*.*'
}
def CreateMenu(self):
fileMenu = wx.Menu()
item = fileMenu.Append(wx.ID_ABOUT, '&About', 'Info')
self.Bind(wx.EVT_MENU, self.OnAbout, item)
item = fileMenu.Append( wx.ID_OPEN, '&Open', 'Info')
self.Bind(wx.EVT_MENU, self.OnOpen, item)
item = fileMenu.Append(wx.ID_SAVE, '&Save', 'Info')
self.Bind(wx.EVT_MENU, self.OnSave, item)
item = fileMenu.Append(wx.ID_SAVEAS, 'Save &As', 'Info')
self.Bind(wx.EVT_MENU, self.OnSaveAs, item)
#
# psst: Hey put the print menu here!!!!
# psst: do the binding here!!!!
#
fileMenu.AppendSeparator()
item = fileMenu.Append(wx.ID_EXIT, 'E&xit', 'Exit')
self.Bind(wx.EVT_MENU, self.OnExit, item)
menuBar = wx.MenuBar()
# Add the fileMenu to the MenuBar
menuBar.Append(fileMenu, '&File')
# Add the menuBar to the Frame
self.SetMenuBar(menuBar)
def askUserForFilename(self, **kw):
dialog = wx.FileDialog(self, **kw)
if dialog.ShowModal() == wx.ID_OK:
userProvidedFilename = True
self.filename = dialog.GetFilename()
self.dirname = dialog.GetDirectory()
self.SetTitle('Editor %s'%(self.filename))
else:
userProvidedFilename = False
dialog.Destroy()
return userProvidedFilename
def OnAbout(self, event):
dialog = wx.MessageDialog(
self,
'A sample editor in wxPython',
'About Sample Editor',
wx.OK
)
dialog.ShowModal()
dialog.Destroy()
def OnExit(self, event):
self.Close()
def OnSave(self, event):
textfile = open(os.path.join(self.dirname, self.filename),
'w')
textfile.write(self.control.GetValue())
textfile.close()
def OnOpen(self, event):
if self.askUserForFilename(
style=wx.OPEN,
**self.dlgdefaults
):
textfile = open(os.path.join(self.dirname, self.filename),
'r')
self.control.SetValue(textfile.read())
textfile.close()
def OnSaveAs(self, event):
if self.askUserForFilename(
defaultFile=self.filename,
style=wx.SAVE,
**self.dlgdefaults
):
self.OnSave(event)
def OnPrint(self, event):
sys.stdout.write(self.control.GetValue())
app = wx.App()
frame = MainWindow()
frame.Show()
app.MainLoop()
#--ENDCODE--#
More information about the Python-list
mailing list