storing file path using windows explorer browser in python

半城伤御伤魂 提交于 2019-12-08 13:50:40

问题


I have written some encryption code in python that takes raw input message from user and then encrypts and decrypts it using AES. Now i want to enhance the working and i want that i can open the windows explorer from my code and browse to any file on my computer, select it and when i press OK button the path to file is stored in a variable so i can use it for processing.

I have search many forums, i have managed to open windows explorer but there is no traditional OK and Cancel button. If user presses OK button the path to the file should be stored in my code variable.

Any help in this regard will be highly appreciated.

moreover, just to let you know i have used the following code:

import os
os.system("start .")

but the explorer window doesnt have any cancel or OK button. Please help


回答1:


That is because what you see when you open files in Windows is not actually an Explorer window, it is called a common dialog. I am assuming you are referering to this dialog:

There are different ways you can go about opening the common open dialog, among the most easiest is probably just using the Tkinter module from the Python standard library, namely the tkFileDialog module's askopenfilename.

Example code:

import Tkinter
import tkFileDialog

root = Tkinter.Tk()
root.withdraw()

filename = tkFileDialog.askopenfilename(parent=root,title='Open file to encrypt')

As for the curly braces: You are using askopenfilenames to tell Tk that you possibly want more than one filename. That's why you get a list of filenames enclosed in curly braces. I actually suspect an oversight in Python's Tk binding so that the filenames are not split up and a list is returned, but this is easily remedied using code similar to this:

import re
# ...
# ...
filenames = tkFileDialog.askopenfilenames(parent=root)
files_to_process = re.split("\}\W\{", filenames[1:-1])

This will give you a list of the selected filenames in case the user selects more than one file. It will break when only passed a single filename, so be sure to check for that case.



来源:https://stackoverflow.com/questions/3643418/storing-file-path-using-windows-explorer-browser-in-python

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!