首页 > 解决方案 > 如何使用 tkinter filedialog.askopenfilename 方法避免文件选择器中的隐藏文件?

问题描述

我想允许用户从文件管理器中选择 CSV 文件。但是它也显示了所有隐藏的文件夹,这是非常不合适的。如何避免隐藏文件夹?

def importCSV(self):
            self.file =  filedialog.askopenfilename(initialdir = "/",title = "Select file",filetypes = (("CSV files","*.csv"),("all files","*.*")))

标签: pythonpython-3.xtkinter

解决方案


经过一番搜索,我设法在这里找到了答案。我对链接的示例做了一些细微的更改,以便它可以在 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'.


推荐阅读