Save File Dialog Box in Tkinter

在python 下的 tkinter 叫出 save as 對話框,取得要存檔的名稱。

from tkinter import *
from tkinter.filedialog import asksaveasfile

win= Tk()
win.geometry("750x250")
def save_file():
   f = asksaveasfile(initialfile = 'Untitled.txt',
defaultextension=".txt",filetypes=[("All Files","*.*"),("Text Documents","*.txt")])

btn= Button(win, text= "Save", command= lambda:save_file())
btn.pack(pady=10)

win.mainloop()

使用起來還滿簡單的。

範例2:

from tkinter import *
from tkinter import filedialog
#setting up parent window
root = Tk()

#function definition for opening file dialog
def savef():
    myFile = filedialog.asksaveasfile(mode='w', defaultextension='.txt')
    if myFile is None:
        return
    data = teditor.get(1.0,'end')
    myFile.write(data)
    myFile.close()

說明:asksaveasfile 會取得 file, asksaveasfilename 才是取得 string.

範例3:

from tkinter.filedialog import asksaveasfile
from tkinter import *

base = Tk()

def SaveFile():
   data = [('All tyes(*.*)', '*.*'),("csv file(*.csv)","*.csv")]
   file = asksaveasfilename(filetypes = data, defaultextension = data)
   # file will have file name provided by user.
   # Now we can use this file name to save file.
   with open(file,"w") as f:
      f.write(<data you want to save>)

save_btn = Button(base, text = 'Click to save file ', command = SaveFile)
save_btn.pack(side = TOP, pady = 20,padx = 50)

base.mainloop()

發佈留言

發佈留言必須填寫的電子郵件地址不會公開。 必填欄位標示為 *