Python3 tkinter 实现文件读取及保存功能

yipeiwu_com5年前Python基础

tkinter介绍

tkinter是python自带的GUI库,是对图形库TK的封装

tkinter是一个跨平台的GUI库,开发的程序可以在win,linux或者mac下运行

# !/user/bin/env Python3
# -*- coding:utf-8 -*-
 
"""
file:window.py.py
create time:2019/6/27 14:54
author:Loong Xu
desc: 窗口
"""
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() # 显示

总结

以上所述是小编给大家介绍的Python3 tkinter 实现文件读取及保存功能,希望对大家有所帮助,如果大家有任何疑问请给我留言,小编会及时回复大家的。在此也非常感谢大家对【听图阁-专注于Python设计】网站的支持!
如果你觉得本文对你有帮助,欢迎转载,烦请注明出处,谢谢!

相关文章

Python实现的多项式拟合功能示例【基于matplotlib】

Python实现的多项式拟合功能示例【基于matplotlib】

本文实例讲述了Python实现的多项式拟合功能。分享给大家供大家参考,具体如下: # -*- coding: utf-8 -*- #! python2 import numpy as...

Python selenium 父子、兄弟、相邻节点定位方式详解

今天跟大家分享下selenium中根据父子、兄弟、相邻节点定位的方法,很多人在实际应用中会遇到想定位的节点无法直接定位,需要通过附近节点来相对定位的问题,但从父节点定位子节点容易,从子节...

Python中operator模块的操作符使用示例总结

operator模块是python中内置的操作符函数接口,它定义了一些算术和比较内置操作的函数。operator模块是用c实现的,所以执行速度比python代码快。 逻辑操作 fr...

Python unittest单元测试框架总结

什么是单元测试 单元测试是用来对一个模块、一个函数或者一个类来进行正确性检验的测试工作。 比如对于函数abs(),我们可以编写的测试用例为: (1)输入正数,比如1、1.2、0.99,期...

OpenCV HSV颜色识别及HSV基本颜色分量范围

OpenCV HSV颜色识别及HSV基本颜色分量范围

一般对颜色空间的图像进行有效处理都是在HSV空间进行的,然后对于基本色中对应的HSV分量需要给定一个严格的范围,下面是通过实验计算的模糊范围(准确的范围在网上都没有给出)。 H: &nb...