Python-tkinter实现简单的文本编辑器
利用tkinter实现简单的文本编辑器。创建一个简单的文本编辑器。可以用读文件的方式在一个文本域里显示一些文字供用户编辑。
当用户退出程序时(通过 QUIT 按钮)会询问用户是否保存所作的修改。
(直接上代码~有注释~)
1 #-*- encoding: utf-8 -*-
2 ‘‘‘
3 @File : 简单文本编辑器.py4 @Time : 2020/04/05 11:35:395 @Author : Konggu6 @Desc : None7 ‘‘‘
8 importos9 importtkinter as tk10 importtkinter.messagebox11 from functools importpartial as pto12 from tkinter importfiledialog, dialog13
14 path = r‘F:\Python\网络通信编程技术(2020-3-5)\第五周作业\\‘
15 file_text = ‘‘
16 window =tk.Tk()17 window.title(‘啊嘞嘞?‘) #窗口标题
18 window.geometry(‘500x300‘) #窗口尺寸
19 t1 = tk.Text(window, width=50, height=10, bg=‘palegreen‘, font=(12))20 t1.pack()21
22 #打开文件
23 defopen_file():24 file_path = filedialog.askopenfilename(title=u‘选择文件‘, initialdir=(os.path.expanduser(path))) #文件选择框(选择文件)
25 with open(file=file_path, mode=‘r+‘, encoding=‘utf-8‘) as f:26 file_text = f.read() #读文件
27 t1.insert(‘insert‘, file_text)28
29 #保存文件
30 defsave():31 file_path = path + ‘文件.txt‘ #指定一个路径
32 file_text = t1.get(‘1.0‘, tk.END)33 if file_path is notNone:34 with open(file=file_path, mode=‘w‘, encoding=‘utf-8‘) as f: #保存到指定路径
35 f.write(file_text)36 t1.delete(‘1.0‘, tk.END)37 print("保存成功")38 tkinter.messagebox.showinfo(title=‘提示‘,message=‘保存成功!‘)39
40 #退出
41 defquit():42 res = tk.messagebox.askokcancel(title = ‘等一下!‘,message=‘保存一手吗?‘) #弹出框,可选(确定/取消)
43 print(res)44 ifres:45 save()46 window.quit()47 else:48 pass
49
50 defmain():51 bt1 = tk.Button(window, text=‘打开文件‘, width=15, height=2, command=open_file)52 bt1.pack()53 bt2 = tk.Button(window, text=‘退出‘, width=15, height=2, command=quit)54 bt2.pack()55 window.mainloop()56
57
58 if __name__ == "__main__":59 main()
最后的效果:
单击 “打开文件” :
“文件.txt” 里的内容:
选择 “文件.txt” 打开,效果:
可以在上面的文本框里进行编辑:
当单击 “退出” 时,弹出 “是否保存文件” 的对话框:
单击确定即可在原文件保存:
然后我们看到,“文件.txt” 里的内容已经改变:
(如果有错误,欢迎指正!谢谢!)
原文地址:https://www.cnblogs.com/kong-gu/p/12650222.html