python tkinter中TXT文件的打开和保存

效果如下图:

# txt文件的打开和保存
import tkinter as tk
from tkinter import filedialog, dialog
import os
 
window = tk.Tk()
window.title('窗口标题') # 标题
window.geometry('500x500') # 窗口尺寸
 
file_path = ''
 
file_text = ''
 
text1 = tk.Text(window, width=50, height=10, bg='orange', font=('Arial', 12))
text1.pack()
 
def open_file():
  '''
  打开文件
  :return:
  '''
  global file_path
  global file_text
  file_path = filedialog.askopenfilename(title=u'选择文件', initialdir=(os.path.expanduser('H:/')))
  print('打开文件:', file_path)
  if file_path is not None:
    with open(file=file_path, mode='r+', encoding='utf-8') as file:
      file_text = file.read()
    text1.insert('insert', file_text)
 
def save_file():
  global file_path
  global file_text
  file_path = filedialog.asksaveasfilename(title=u'保存文件')
  print('保存文件:', file_path)
  file_text = text1.get('1.0', tk.END)
  if file_path is not None:
    with open(file=file_path, mode='a+', encoding='utf-8') as file:
      file.write(file_text)
    text1.delete('1.0', tk.END)
    dialog.Dialog(None, {'title': 'File Modified', 'text': '保存完成', 'bitmap': 'warning', 'default': 0,
               'strings': ('OK', 'Cancle')})
    print('保存完成')
 
bt1 = tk.Button(window, text='打开文件', width=15, height=2, command=open_file)
bt1.pack()
bt2 = tk.Button(window, text='保存文件', width=15, height=2, command=save_file)
bt2.pack()
 
window.mainloop() # 显示
  • 0
    点赞
  • 2
    收藏
    觉得还不错? 一键收藏
  • 1
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值