我想让用户从文件管理器中选择 CSV 文件。但是它也显示所有隐藏文件夹,这是非常不合适的。如何避免隐藏文件夹?
def importCSV(self):
self.file = filedialog.askopenfilename(initialdir = "/",title = "Select file",filetypes = (("CSV files","*.csv"),("all files","*.*")))
最佳答案
经过一番搜索,我设法找到了答案 here .我对链接的示例做了一些细微的更改,以便它可以在 Python 3 上运行。要对其进行测试,只需在执行后按 ctrl+o
。
from tkinter import *
from tkinter import filedialog
root = Tk()
try:
# call a dummy dialog with an impossible option to initialize the file
# dialog without really getting a dialog window; this will throw a
# TclError, so we need a try...except :
try:
root.tk.call('tk_getOpenFile', '-foobarbaz')
except TclError:
pass
# now set the magic variables accordingly
root.tk.call('set', '::tk::dialog::file::showHiddenBtn', '1')
root.tk.call('set', '::tk::dialog::file::showHiddenVar', '0')
except:
pass
# a simple callback for testing:
def openfile(event):
fname = filedialog.askopenfilename(initialdir='/', title='Select file', filetypes=(('CSV files', '*.csv'), ('all files', '*.*')))
print(fname)
root.bind('<Control-o>', openfile)
root.mainloop()
showHiddenVar
用于选择是否默认显示隐藏文件。如果您不想让用户在显示和隐藏隐藏文件之间切换,则只需将 showHiddenBtn
设置为 '0'
。
关于python - 如何使用 tkinter filedialog.askopenfilename 方法避免文件选择器中的隐藏文件?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/53220711/