python保存路径,在python中使用Windows资源管理器浏览器存储文件路径

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

解决方案

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:

pLfOH.png

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.

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值