python - 如何使用 tkinter filedialog.askopenfilename 方法避免文件选择器中的隐藏文件?
问题描述
我想允许用户从文件管理器中选择 CSV 文件。但是它也显示了所有隐藏的文件夹,这是非常不合适的。如何避免隐藏文件夹?
def importCSV(self):
self.file = filedialog.askopenfilename(initialdir = "/",title = "Select file",filetypes = (("CSV files","*.csv"),("all files","*.*")))
解决方案
经过一番搜索,我设法在这里找到了答案。我对链接的示例做了一些细微的更改,以便它可以在 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'
.
推荐阅读
- c# - 子目录中带有 Wordpress 的 Asp.Net MVC Core 2 网站
- r - JAGS 错误消息 - 节点与父节点不一致
- apache-spark - 使用 Kafka 和 Spark Streaming 为 Web 应用程序提供服务
- android - 自定义 Table-like ViewGroup
- php - 从会话中获取所有闪存数据
- android - ADB shell 命令取消和删除我的应用程序中的所有作业
- android - ConstraintLayout,添加约束会移动我的所有元素
- git - 为作曲家包创建差异补丁
- angular - 在 Angular 2 中以动态形式填充下拉列表
- ruby-on-rails - 关于 Ruby on Rails 上的辅助方法