仅接受一种文件类型 [英] Only one file type to be accepted
问题描述
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"))
错误:
回溯(最近通话最近):文件 "D:\ python_projects \ csv_codes \ csv_reading.py",第4行,在 filename = fd.askopenfilename(title =选择文件",文件类型=("CSV文件","*.csv"))文件"C:\ Python \ lib \ tkinter \ filedialog.py", 第375行,在askopenfilename中 在显示中返回Open(** options).show()文件"C:\ Python \ lib \ tkinter \ commondialog.py",第43行 s = w.tk.call(self.command, w._options(self.options)) _tkinter.TclError:文件类型" .csv"错误,应为"typeName {扩展名?扩展名...?}?{macType?macTypes ...?}?"
Traceback (most recent call last): File "D:\python_projects\csv_codes\csv_reading.py", line 4, in filename = fd.askopenfilename(title = "Select file",filetypes = ("CSV Files" ,"*.csv")) File "C:\Python\lib\tkinter\filedialog.py", line 375, in askopenfilename return Open(**options).show() File "C:\Python\lib\tkinter\commondialog.py", line 43, in show s = w.tk.call(self.command, w._options(self.options)) _tkinter.TclError: bad file type ".csv", should be "typeName {extension ?extens ions ...?} ?{macType ?macTypes ...?}?"
我到底想要什么?:
我只希望选择.CSV
个文件. (必修)
I want only .CSV
files to be selected. (compulsory)
推荐答案
filetypes
必须是一个元组的元组.例如:
filetypes
needs to be a tuple of tuples. For example:
from tkinter import filedialog as fd
filename = fd.askopenfilename(title = "Select file",filetypes = (("CSV Files","*.csv"),))
但是我建议您在一个窗口中将所有内容整洁.例如,输入与您相同,但更整齐:
But I suggest you make it all neat and in one window. For example, same input as yours but tidier:
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()
这篇关于仅接受一种文件类型的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!