如何用Python创建Windows现代版「打开文件夹」对话框
在Python中调用IFileOpenDialog实现现代文件夹选择对话框
你可以通过pywin32调用Windows原生的IFileOpenDialog COM接口,实现符合需求的现代文件夹选择对话框——界面和系统原生保持一致,支持以上次选中路径作为初始打开位置,直观友好。
实现步骤与代码示例
- 先安装依赖的pywin32库:
pip install pywin32
- 完整实现代码:
import win32com.client from win32com.shell import shell, shellcon import os def select_folder(initial_dir=None): # 初始化现代文件选择对话框实例 dialog = win32com.client.Dispatch("FileOpenDialog") # 配置对话框为文件夹选择模式,仅允许真实文件系统路径,且路径必须存在 dialog.SetOptions(shellcon.FOS_PICKFOLDERS | shellcon.FOS_FORCEFILESYSTEM | shellcon.FOS_PATHMUSTEXIST) # 设置初始打开路径(如果传入的路径存在) if initial_dir and os.path.isdir(initial_dir): dialog.SetFolder(initial_dir) # 显示对话框,等待用户操作 if dialog.Show() == shellcon.S_OK: # 获取选中文件夹的真实文件系统路径 selected_path = dialog.GetResult().GetDisplayName(shellcon.SIGDN_FILESYSPATH) # 将选中路径保存到本地文件,下次作为初始路径使用 with open("last_selected_folder.txt", "w", encoding="utf-8") as f: f.write(selected_path) return selected_path return None # 读取上次保存的选中路径 last_selected = None if os.path.exists("last_selected_folder.txt"): with open("last_selected_folder.txt", "r", encoding="utf-8") as f: last_selected = f.read().strip() # 调用对话框 selected_folder_path = select_folder(last_selected) if selected_folder_path: print(f"选中的文件夹:{selected_folder_path}") else: print("用户取消了选择")
关键参数说明
shellcon.FOS_PICKFOLDERS:将对话框切换为文件夹选择模式,而非文件选择shellcon.FOS_FORCEFILESYSTEM:限制用户只能选择真实存在的文件系统文件夹,排除虚拟路径(如控制面板项)shellcon.FOS_PATHMUSTEXIST:确保设置的初始路径是有效的,避免对话框打开报错SetFolder():指定对话框打开时的初始位置GetDisplayName(shellcon.SIGDN_FILESYSPATH):获取选中文件夹的标准文件系统路径,而非显示名称
注意事项
- 该方案仅适用于Windows系统,依赖Windows原生COM接口
- 保存上次路径的逻辑可根据需求调整,比如使用JSON配置文件存储更多设置,而非简单的文本文件
内容的提问来源于stack exchange,提问作者Josef
相关产品推荐
相关产品推荐

