python写的一个文本编辑器
#!/usr/bin/env python
#-*- coding: utf-8 -*-
#=============================================================================
# filename:
# desc:
# author: toughguy
# version: 0.0.1
# lastchange: 2013-02-20 14:52:11
# history:
#=============================================================================
from tkinter import *
import tkmessagebox,tkfiledialog
import platform
# nl = os.linesep
def openfile():
global filename # 使用global声明为全局变量,方便后边的程序调用
systype = platform.system() # 判断系统类型
if systype == 'windows':
basedir = 'c:\\'
else:
basedir = '/'
filename = tkfiledialog.askopenfilename(initialdir=basedir)
try:
fobj_r = open(filename, 'r')
except ioerror, errmsg:
print '*** failed open file:', errmsg
else:
editbox.delete(1.0, end)
for eachline in fobj_r:
editbox.insert(insert, eachline)
fobj_r.close()
def savefile():
save_data = editbox.get(1.0, end)
try:
fobj_w = open(filename, 'w')
fobj_w.writelines(save_data.encode('utf-8'))
fobj_w.close()
tkmessagebox.showinfo(title='提示',
message='保存成功')
except ioerror, errmsg:
tkmessagebox.showwarning(title='保存失败', message='保存出错 ')
tkmessagebox.showwarning(title='错误信息', message=errmsg)
except nameerror:
tkmessagebox.showwarning(title='保存失败', message='未打开文件')
def showlinenum():
tkmessagebox.showinfo(title='提示',
message='这个功能作者现在不会写,放这里装饰用的.')
def destroy_ui(ui):
ui.destroy()
def aboutauthor():
author_ui = toplevel()
author_ui.title('关于')
author_ui.geometry('200x80')
about_string = label(author_ui,
text="作者: toughguy")
confirmbtn = button(author_ui, text='确定',
command=lambda:destroy_ui(author_ui))
about_string.pack()
confirmbtn.pack()
# author_ui.mainloop()
def createmenus():
# 初始化菜单
menubar = menu(root)
# 创建文件菜单
filemenu = menu(menubar, tearoff=0)
filemenu.add_command(label='打开文件', command=openfile)
filemenu.add_command(label='保存文件', command=savefile)
filemenu.add_command(label='退出', command=lambda:destroy_ui(root))
menubar.add_cascade(label='文件', menu=filemenu)
# 创建编辑菜单
editmenu = menu(menubar, tearoff=0)
editmenu.add_command(label='显示行号', command=showlinenum)
menubar.add_cascade(label='编辑', menu=editmenu)
# 创建帮助菜单
helpmenu = menu(menubar, tearoff=0)
helpmenu.add_command(label='关于作者', command=aboutauthor)
menubar.add_cascade(label='帮助', menu=helpmenu)
root.config(menu=menubar)
root = tk()
root.title('文本编辑器')
root.geometry('500x400')
createmenus()
editbox = text(root, width=70, height=25, bg='white')
editbox.pack(side=top, fill=x)
root.mainloop()
推荐阅读