简体   繁体   中英

I want to use extensions list at the time of “save as” option in File Dialog for file write in Python 3

I want to use extensions list example : [".txt",".html",".css"] for save as option in file dialog popup window. when I use this method

file_opt = options = {}
options['defaultextension'] = '.txt'
,I can able to write any file with .txt as default extension without choose in save as option but I want to choose extensions for save as in file dialog popup window from using my extensions list. I'm using Python 3.5 based Anaconda IDE

If you look at the documentation here you can see that you can pass in the filetypes keyword which specifies a list of tuples that have the name, and file extension respectively for the different types of filetypes you want to be able to save as.. So you can do something along the lines of:

import tkinter as tk
from tkinter import filedialog as fd

def save_file():

    filename = fd.asksaveasfilename(defaultextension='.txt', 
         filetypes= [('Text','.txt'), ('HTML', '.html'), ('CSS', '.css')])
    if filename:
        print("User saved the filename with extension:", filename.split(".")[-1])

root = tk.Tk()
button = tk.Button(root, text='Save File', command=save_file)
button.pack()
root.mainloop()

Or if you really want to use a dictionary for this:

import tkinter as tk
from tkinter import filedialog as fd

SAVE_OPTS = {'defaultextension':'.txt', 
             'filetypes': [('Text','.txt'), ('HTML', '.html'), ('CSS', '.css')]}

def save_file():

    filename = fd.asksaveasfilename(**SAVE_OPTS)
    if filename:
        print("User saved the filename with extension:", filename.split(".")[-1])

root = tk.Tk()
button = tk.Button(root, text='Save File', command=save_file)
button.pack()
root.mainloop()
SaveFileDialog sd = new SaveFileDialog();
sd.Filter = "Text File (*.txt)|*.txt|PNG File (*.txt)|*.png"|...;

if(sd.ShowDialog() == DialogResult.OK) {
    richTextBox1.SaveFile(sd.FileName, RichTextBoxStreamType.PlainText);
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM