赞
踩
用到的两个函数
filedialog.askopenfilename()
filedialog.asksaveasfile()
注意filedialog.askopenfilename()返回的是文件名,而filedialog.asksaveasfile()返回的是打开的文件。
创建文本框
text_file = Text(frame_left_top)
获得文本框中的文字
str1 = text_file.get(1.0,END)
button_open = Button(frame_right,width=7,height=1,text=‘Open’,command=funcOpen)
frame_left_top = Frame(width=380,height=370,bg=‘white’)
frame_left_top.grid(row=0,column=0,padx=2,pady=5)
from tkinter import * from tkinter import filedialog def funcOpen(): global fname text_file.delete(1.0,END) fname = filedialog.askopenfilename(initialdir = "./",filetypes=[('TXT','.txt')]) with open(fname,'r') as f1: str1=f1.read() text_file.insert(0.0,str1) f1.close() def funcSave(): str1 = text_file.get(1.0,END) with open(fname,'w') as f1: f1.write(str1) f1.close() def funcSaveAs(): f1 = filedialog.asksaveasfile(initialdir = "./",filetypes=[('TXT','.txt')],defaultextension='.txt') str1 = text_file.get(1.0,END) f1.write(str1) f1.close() root = Tk() root.title("File save and open") frame_left_top = Frame(width=380,height=370,bg='white') frame_right = Frame(width=70,height=370) text_file = Text(frame_left_top) button_open = Button(frame_right,width=7,height=1,text='Open',command=funcOpen) button_save = Button(frame_right,width=7,height=1,text='Save',command=funcSave) button_save_as = Button(frame_right,width=7,height=1,text='Save as',command=funcSaveAs) frame_left_top.grid(row=0,column=0,padx=2,pady=5) frame_right.grid(row=0,column=1,rowspan=3,padx=4,pady=5) frame_left_top.grid_propagate(0) frame_right.grid_propagate(0) text_file.grid() button_open.grid(padx=2,pady=2,sticky = 'SE') button_save.grid(padx=2,pady=2,sticky = 'SE') button_save_as.grid(padx=2,pady=2,sticky = 'SE') mainloop()
主界面如下图
单击打开就会跳转到Windows打开界面。
Copyright © 2003-2013 www.wpsshop.cn 版权所有,并保留所有权利。