将 python 文件对话框限制为特定的文件类型 [英] Limiting python filedialog to a specific filetype

查看:78
本文介绍了将 python 文件对话框限制为特定的文件类型的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我创建了以下试用代码来制作一个程序,该程序将一个 Excel 工作表加载到一个数据框中,然后将该数据框保存到另一个 Excel 工作表中(所有用户选择)

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()

我想做的是扩展它,这样当程序弹出文件目录窗口时,它只显示 .xlsx 文件类型的文件,以避免用户打开不兼容的文件类型时出错.到目前为止,我还没有想出任何可以解释如何正确设置的信息.

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.

推荐答案

事实证明顺序很重要.此外,答案必须包括文件类型周围的 [].有问题的两行必须是

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()))

这篇关于将 python 文件对话框限制为特定的文件类型的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆