python基于tkinter库实现简单文本编辑器实例

本文实例讲述了python基于tkinter库实现简单文本编辑器的方法。分享给大家供大家参考。具体实现方法如下:

## {{{ http://code.activestate.com/recipes/578568/ (r1)
from tkinter import *
from tksimpledialog import askstring
from tkfiledialog import asksaveasfilename
from tkmessagebox import askokcancel
class quitter(frame):
def __init__(self, parent=none):
frame.__init__(self, parent)
self.pack()
widget = button(self, text=’quit’, command=self.quit)
widget.pack(expand=yes, fill=both, side=left)
def quit(self):
ans = askokcancel(‘verify exit’, “really quit?”)
if ans: frame.quit(self)
class scrolledtext(frame):
def __init__(self, parent=none, text=”, file=none):
frame.__init__(self, parent)
self.pack(expand=yes, fill=both)
self.makewidgets()
self.settext(text, file)
def makewidgets(self):
sbar = scrollbar(self)
text = text(self, relief=sunken)
sbar.config(command=text.yview)
text.config(yscrollcommand=sbar.set)
sbar.pack(side=right, fill=y)
text.pack(side=left, expand=yes, fill=both)
self.text = text
def settext(self, text=”, file=none):
if file:
text = open(file, ‘r’).read()
self.text.delete(‘1.0’, end)
self.text.insert(‘1.0’, text)
self.text.mark_set(insert, ‘1.0’)
self.text.focus()
def gettext(self):
return self.text.get(‘1.0′, end+’-1c’)
class simpleeditor(scrolledtext):
def __init__(self, parent=none, file=none):
frm = frame(parent)
frm.pack(fill=x)
button(frm, text=’save’, command=self.onsave).pack(side=left)
button(frm, text=’cut’, command=self.oncut).pack(side=left)
button(frm, text=’paste’, command=self.onpaste).pack(side=left)
button(frm, text=’find’, command=self.onfind).pack(side=left)
quitter(frm).pack(side=left)
scrolledtext.__init__(self, parent, file=file)
self.text.config(font=(‘courier’, 9, ‘normal’))
def onsave(self):
filename = asksaveasfilename()
if filename:
alltext = self.gettext()
open(filename, ‘w’).write(alltext)
def oncut(self):
text = self.text.get(sel_first, sel_last)
self.text.delete(sel_first, sel_last)
self.clipboard_clear()
self.clipboard_append(text)
def onpaste(self):
try:
text = self.selection_get(selection=’clipboard’)
self.text.insert(insert, text)
except tclerror:
pass
def onfind(self):
target = askstring(‘simpleeditor’, ‘search string?’)
if target:
where = self.text.search(target, insert, end)
if where:
print where
pastit = where + (‘+%dc’ % len(target))
#self.text.tag_remove(sel, ‘1.0’, end)
self.text.tag_add(sel, where, pastit)
self.text.mark_set(insert, pastit)
self.text.see(insert)
self.text.focus()
if __name__ == ‘__main__’:
try:
simpleeditor(file=sys.argv[1]).mainloop()
except indexerror:
simpleeditor().mainloop()

希望本文所述对大家的python程序设计有所帮助。

Posted in 未分类

发表评论