【问题标题】:Only one file type to be accepted只接受一种文件类型
【发布时间】:2019-02-10 12:31:35
【问题描述】:
from tkinter import filedialog as fd

filename = fd.askopenfilename(title = "Select file",filetypes = (("CSV Files","*.csv"),("All","*.*")))

打开文件夹选择文件,但是当我尝试时:

from tkinter import filedialog as fd

filename = fd.askopenfilename(title = "Select file",filetypes = ("CSV Files","*.csv"))

错误:

Traceback(最近一次调用最后一次):文件 “D:\python_projects\csv_codes\csv_reading.py”,第 4 行,在 文件名 = fd.askopenfilename(title = "选择文件",filetypes = ("CSV Files" ,"*.csv")) 文件 "C:\Python\lib\tkinter\filedialog.py", 第 375 行,在 askopenfilename 中 返回 Open(**options).show() 文件“C:\Python\lib\tkinter\commondialog.py”,第 43 行,在 show s = w.tk.call(self.command, w._options(self.options)) _tkinter.TclError: bad file type ".csv", 应该是 "typeName {extension ?extension ions ...?} ?{macType ?macTypes ...?}?"

我到底想要什么?:

我只想选择 .CSV 文件。 (强制)

【问题讨论】:

    标签: python python-3.x tkinter filedialog


    【解决方案1】:

    filetypes 必须是元组的元组。例如:

    from tkinter import filedialog as fd
    
    filename = fd.askopenfilename(title = "Select file",filetypes = (("CSV Files","*.csv"),))
    

    但我建议您将所有内容都整齐地放在一个窗口中。例如,与您的输入相同但更整洁:

    from tkinter import *
    from tkinter import filedialog as fd
    
    def get_file_name(file_entry):
        file_name = fd.askopenfilename(title = "Select file",filetypes = (("CSV Files","*.csv"),))
        file_entry.delete(0,END)
        file_entry.insert(0,file_name)
    
    def run_and_close(event=None):
        ######################################
        ## EXECUTE OR CALL OTHER PYTHON FILE##
        ######################################
        close()
    
    def close(event=None):
        master.withdraw() # if you want to bring it back
        sys.exit() # if you want to exit the entire thing
    
    master = Tk()
    master.title("This is my Interface")
    
    entry_csv=Entry(master, text="", width=50)
    entry_csv.grid(row=0, column=1, sticky=W, padx=5)
    
    Label(master, text="Input CSV").grid(row=0, column=0 ,sticky=W)
    Button(master, text="Browse...", width=10, command=lambda:get_file_name(entry_csv)).grid(row=0, column=2, sticky=W)
    
    Button(master, text="Ok",     command=run_and_close, width=10).grid(row=3, column=1, sticky=E, padx=5)
    Button(master, text="Cancel", command=close, width=10).grid(row=3, column=2, sticky=W)
    
    master.bind('<Return>', run_and_close)
    master.bind('<Escape>', close)
    mainloop()
    

    【讨论】:

    猜你喜欢
    • 2016-11-08
    • 1970-01-01
    • 2017-07-17
    • 1970-01-01
    • 2019-02-02
    • 1970-01-01
    • 2017-11-17
    • 2016-09-23
    • 2016-01-01
    相关资源
    最近更新 更多