Python3 tkinter 实现文件读取及保存

2019/07/30 20:03
阅读数 53

转载自:https://blog.csdn.net/u013032852/article/details/93996709

 1 # !/user/bin/env Python3
 2 # -*- coding:utf-8 -*-
 3  
 4 """
 5 file:window.py.py
 6 create time:2019/6/27 14:54
 7 author:Loong Xu
 8 desc: 窗口
 9 """
10 import tkinter as tk
11 from tkinter import filedialog, dialog
12 import os
13  
14 window = tk.Tk()
15 window.title('窗口标题')  # 标题
16 window.geometry('500x500')  # 窗口尺寸
17  
18 file_path = ''
19  
20 file_text = ''
21  
22 text1 = tk.Text(window, width=50, height=10, bg='orange', font=('Arial', 12))
23 text1.pack()
24  
25  
26 def open_file():
27     '''
28     打开文件
29     :return:
30     '''
31     global file_path
32     global file_text
33     file_path = filedialog.askopenfilename(title=u'选择文件', initialdir=(os.path.expanduser('H:/')))
34     print('打开文件:', file_path)
35     if file_path is not None:
36         with open(file=file_path, mode='r+', encoding='utf-8') as file:
37             file_text = file.read()
38         text1.insert('insert', file_text)
39  
40  
41 def save_file():
42     global file_path
43     global file_text
44     file_path = filedialog.asksaveasfilename(title=u'保存文件')
45     print('保存文件:', file_path)
46     file_text = text1.get('1.0', tk.END)
47     if file_path is not None:
48         with open(file=file_path, mode='a+', encoding='utf-8') as file:
49             file.write(file_text)
50         text1.delete('1.0', tk.END)
51         dialog.Dialog(None, {'title': 'File Modified', 'text': '保存完成', 'bitmap': 'warning', 'default': 0,
52                              'strings': ('OK', 'Cancle')})
53         print('保存完成')
54  
55  
56 bt1 = tk.Button(window, text='打开文件', width=15, height=2, command=open_file)
57 bt1.pack()
58 bt2 = tk.Button(window, text='保存文件', width=15, height=2, command=save_file)
59 bt2.pack()
60  
61 window.mainloop()  # 显示

 

展开阅读全文
打赏
0
0 收藏
分享
加载中
更多评论
打赏
0 评论
0 收藏
0
分享
返回顶部
顶部