Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Limiting python filedialog to a specific filetype

I created the following trial code to make a program that will load an excel sheet into a dataframe and then save that dataframe to another excel sheet (all of the user's choosing)

import os
import pandas
from pandas import ExcelWriter
import tkinter as tk
from tkinter import filedialog

class Load_Save_Program():

    def __init__(self,master):
        self.master = master

        self.button1=tk.Button(self.master,text="Load",command=self.Load_file)
        self.button1.grid(row=0,column=0)

        self.button2=tk.Button(self.master,text="Save",command=self.Save_file)
        self.button2.grid(row=0,column=1)

        self.text=tk.Text(master)
        self.text.grid(row=1,column=0,columnspan=2)

    def Load_file(self):
        self.df_import=pandas.read_excel(filedialog.askopenfilename(initialdir = os.getcwd()),
                                            filetypes=("excel files","*.xlsx"))
        self.text.insert(tk.END,self.df_import)

    def Save_file(self):
        self.writer = ExcelWriter(filedialog.asksaveasfilename(initialdir = os.getcwd()),
                                            filetypes=("Excel files", "*.xlsx"))
        self.df_import.to_excel(self.writer,'sheet1')
        self.writer.save()

root=tk.Tk()
Load_Save_Program(root)
root.mainloop()

What I would like to do is to expand this so that when the program pops up the file directory window, it only shows files that are of the .xlsx filetype as to avoid an error from the user opening up an incompatible file type. So far I've yet to come up with any information that can explain how to set this up properly.

like image 490
jon Avatar asked Sep 20 '17 20:09

jon


2 Answers

The filedalogs have a filetypes option to do exactly what you want. The general syntax is filetypes=[(label1, ext1), (label2, ext2), ...].

In your case that will give:

filedialog.askopenfilename(filetypes=[("Excel files", "*.xlsx")])

like image 66
j_4321 Avatar answered Sep 21 '22 03:09

j_4321


It turns out that the order is important. Additionally, the answer must include the [] around the filetype. The two lines in question must be

self.df_import=pandas.read_excel(filedialog.askopenfilename(filetypes=[("Excel files","*.xlsx")],initialdir = os.getcwd()))
self.writer = ExcelWriter(filedialog.asksaveasfilename(filetypes=[("Excel files", "*.xlsx")],initialdir = os.getcwd()))
like image 31
jon Avatar answered Sep 25 '22 03:09

jon