python 实现弹出文件夹选择 python打开选择文件对话框 您所在的位置:网站首页 python打开文件夹并选中文件的第三方库怎么打开不了 python 实现弹出文件夹选择 python打开选择文件对话框

python 实现弹出文件夹选择 python打开选择文件对话框

2024-07-16 07:03| 来源: 网络整理| 查看: 265

打开对话框选择文件夹tkinter.filedialog.askdirectory()

返回:字符串。【选择文件夹,返回文件夹名(含路径) ;没有选择文件夹,返回空字符串】

打开对话框可能选择文件夹也可能没有选择文件夹,可以在函数里使用条件判断,若没有选择文件夹可以直接退出程序,选择文件夹则继续执行。

from tkinter.filedialog import askdirectory def chooceFolder(): """ 打开对话框选择文件夹,若没有选择文件夹,退出函数,若选择文件夹,继续执行 """ afolder = askdirectory() if afolder == '': return print('已选择文件夹',afolder) # 选择文件夹 chooceFolder() # 返回:已选择文件夹 E:/Program Files (x86)/python/libs # 未选择文件夹 chooceFolder() # 返回:None,即无返回值打开对话框选择文件tkinter.filedialog.askopenfilename()   【选择一个文件】

返回:字符串。【选择文件,返回文件名(含路径含扩展名) ;没有选择文件,返回空字符串】

打开对话框可能选择文件也可能没有选择文件,可以在函数里使用条件判断,若没有选择文件可以直接退出程序,选择文件则继续执行。

from tkinter.filedialog import askopenfilename def chooceFile(): """ 打开对话框选择文件,若没有选择文件,退出函数,若选择文件,继续执行 """ afile = askopenfilename() if afile == '': return print('已选择文件:',afile) # 选择文件 chooceFile() # 返回:已选择文件: E:/Program Files (x86)/python/NEWS.txt # 未选择文件 chooceFile() # 返回:None,即无返回值

可以选择文件类型,打开对话框后,可以通过文件类型更快选择需要的文件。

import tkinter # 选择一种文件类型 afile = tkinter.filedialog.askopenfilename(filetypes=[('text files', '.txt')]) # 若一种文件类型有多个扩展名 afile = tkinter.filedialog.askopenfilename(filetypes=[('Microsoft Excel', ('.xls','.xlsx'))]) # 选择多个文件类型 afile = tkinter.filedialog.askopenfilename(filetypes=[('text files', '.txt'),('python files',('.py','.pyc'))])tkinter.filedialog.askopenfilenames()   【选择多个文件】

返回:元组。

python 实现弹出文件夹选择 python打开选择文件对话框_python

 

打开对话框保存文件tkinter.filedialog.asksaveasfilename()

返回:字符串。【保存文件(注意输入扩展名),返回文件名(含路径) ;没有保存文件,返回空字符串】

# 举例:创建新的EXCEL工作簿,并保存 from tkinter.filedialog import asksaveasfilename import openpyxl wbook = openpyxl.Workbook() afile = asksaveasfilename() wbook.save(afile) # 若保存对话框点击取消或者右上角关闭按钮,则报错如下 Traceback (most recent call last): File "", line 1, in wbook.save(afile) File "E:\Program Files (x86)\python\lib\site-packages\openpyxl\workbook\workbook.py", line 407, in save save_workbook(self, filename) File "E:\Program Files (x86)\python\lib\site-packages\openpyxl\writer\excel.py", line 291, in save_workbook archive = ZipFile(filename, 'w', ZIP_DEFLATED, allowZip64=True) File "E:\Program Files (x86)\python\lib\zipfile.py", line 1249, in __init__ self.fp = io.open(file, filemode) FileNotFoundError: [Errno 2] No such file or directory: ''

若取消保存,后续在文件保存时会有报错,若一定要保存,可用while循环,直到保存为止。

若可以不保存,则尝试捕获异常处理。之前写过捕获异常的文章可以作为参考:【Python】捕获异常

from tkinter.filedialog import asksaveasfilename def saveFile(obj): """ 打开对话框保存文件,若没有保存文件,循环提示直到保存,若保存文件,继续执行 """ afile = asksaveasfilename() while afile == '': afile = asksaveasfilename() obj.save(afile) print('已保存文件:',afile) # 创建新的EXCEL工作簿,并保存 import openpyxl wbook = openpyxl.Workbook() saveFile(wbook) # 返回:已保存文件: G:/python/a.xlsx


【本文地址】

公司简介

联系我们

今日新闻

    推荐新闻

    专题文章
      CopyRight 2018-2019 实验室设备网 版权所有