您的位置:首页 > 编程语言 > Python开发

python2.7练习 写一个简单的文本编辑器

2015-05-06 10:16 477 查看
# -*- coding: utf-8 -*-

import wx, os, sys
class MenuBarWindow(wx.Frame):
def __init__(self, parent, title):

# A "-1" in the size parameter instructs wxWidgets to use the default size.
# In this case, we select 200px width and the default height.
wx.Frame.__init__(self, parent, title=title, size=wx.DefaultSize)
self.control = wx.TextCtrl(self, style=wx.TE_MULTILINE)
# A StatusBar in the bottom of the window
self.CreateStatusBar()

# Setting up the menu.
filemenu = wx.Menu()
# wx.ID_ABOUT and wx.ID_EXIT are standard IDs provided by wxWidgets.
menuAbout = filemenu.Append(wx.ID_ABOUT, "About", " Information about this program")
menuOpen = filemenu.Append(wx.ID_OPEN, "Open", "Open a file to editor")
menuExit = filemenu.Append(wx.ID_EXIT, "Exit", " Terminate the program")
menuSave = filemenu.Append(wx.ID_SAVE, "Save", "Save the file")
# 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.

# Set Events
self.Bind(wx.EVT_MENU, self.OnOpen, menuOpen)
self.Bind(wx.EVT_MENU, self.OnAbout, menuAbout)
self.Bind(wx.EVT_MENU, self.OnExit, menuExit)
self.Bind(wx.EVT_MENU, self.OnSave, menuSave)

self.Show(True)

def OnExit(self, event):
print 'exit'
self.Close(True)
def OnAbout(self, event):
print 'about'
dlg = wx.MessageDialog(self, "A small text editor", "About Sample Editor", wx.OK)
dlg.ShowModal()  # Show it
dlg.Destroy()  # finally destroy it when finished.

def OnOpen(self, event):
print 'open a file'
filepath = ''
try:
dlg = wx.FileDialog(self, "Choose a file", '', '', '*.*', wx.OPEN)
if dlg.ShowModal() == wx.ID_OK:
filename = dlg.GetFilename()
dirname = dlg.GetDirectory()
filepath = os.path.join(dirname, filename)
f = open(filepath, 'r')
self.control.SetValue(f.read())
f.close()
dlg.Destroy()
except IOError:
type, val, traceback = sys.exc_info()
dlg = wx.MessageDialog(self, str(val), "", wx.OK)
dlg.ShowModal()  # Show it
dlg.Destroy()  # finally destroy it when finished.
def OnSave(self, event):
print "save the file"
dlg = wx.FileDialog(self, "save the file", '', '', '*.*', wx.SAVE)
if dlg.ShowModal() == wx.ID_OK:
filename = dlg.GetFilename()
dirname = dlg.GetDirectory()
# get Text content from TextCtrl
data = self.control.GetValue()
dataEncode = data.encode('utf-8')
f = open(os.path.join(dirname, filename), 'w')
f.write(dataEncode)
f.close()
dlg.Destroy()
if __name__ == '__main__':
app = wx.App(False)
frame = MenuBarWindow(None, "My Editor")
app.MainLoop()
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签:  python 文本编辑