from tkinter import *
from tkinter.filedialog import *
import os
filename=''
def mynew():
global filename
txtPad.delete(1.0,'end')#清空所有内容
mysave()#调用保存方法
#打开
def myopen():
global filename
filename=askopenfilename(defaultextension='*.txt')
if filename=='':
filename=None
else:
win.title(''+os.path.basename(filename))
with open(filename,'r')as f:
txtPad.delete(1.0,'end')
txtPad.insert(1.0,f.read())
#保存
def mysave():
global filename
filename=asksaveasfilename(initialfile='未命名.txt',defaultextension='*.txt')
with open(filename,'w') as f:
c=txtPad.get(1.0,'end')
f.write(c)
#撤销
def undo():
global txtPad
txtPad.event_generate("<<Undo>>")
#重做
def redo():
global txtPad
txtPad.event_generate("<<Redo>>")
#剪切
def cut():
global txtPad
txtPad.event_generate("<<Cut>>")
#复制
def copy():
global txtPad
txtPad.event_generate("<<Copy>>")
#粘贴
def paste():
global txtPad
txtPad.event_generate("<<Paste>>")
#右键获取当前的坐标
def popomenu(event):
global txtPad
rightmenu.post(event.x_root,event.y_root)
win = Tk() # 实例化对象
# 设置窗体标题
win.title("记事本")
# 设置窗体大小
win.geometry("600x400+100+50")
# 菜单栏
menubar = Menu(win)
#文件菜单
filemenu=Menu(win)
filemenu.add_command(label='新建',command=mynew)
filemenu.add_command(label='打开',command=myopen)
filemenu.add_command(label='保存',command=mysave)
menubar.add_cascade(label='文件',menu=filemenu)
#编辑菜单
editmenu=Menu(win)
editmenu.add_command(label='撤销',command=undo)
editmenu.add_command(label='重做',command=redo)
editmenu.add_separator()#分割线
editmenu.add_command(label='剪切',command=cut)
editmenu.add_command(label='复制',command=copy)
editmenu.add_command(label='粘贴',command=paste)
menubar.add_cascade(label='编辑',menu=editmenu)
#右键
rightmenu=Menu(win)
rightmenu.add_command(label='复制',command=copy)
rightmenu.add_command(label='剪切',command=cut)
rightmenu.add_command(label='粘贴',command=paste)
win["menu"] = menubar
# 布局的控件
fm = Frame(win, height="20", bg="light sea green")
fm.pack(fill=X)
lb = Label(win, width=2, bg="white")
lb.pack(side=LEFT, fill=Y)
txtPad = Text(win, undo=True, font=("宋体", 20))
txtPad.pack(expand=YES, fill=BOTH)
scroll = Scrollbar(txtPad)
txtPad.config(yscrollcommand=scroll.set)
scroll.config(command=txtPad.yview)
scroll.pack(side=RIGHT, fill=Y)
txtPad.bind('<Button-3>',popomenu)
win.mainloop()
该有的功能基本都有哦!