Python中使用tkFileDialog实现文件选择、保存和路径选择


Posted in Python onMay 20, 2022

使用tkFileDialog实现文件选择、保存和路径选择

概述

看了下Tkinter的文档,对于Pop-up dialog有三类,现在用到的是tkFileDialog

tkFileDialog有三种形式:

  • 一个是:askopenfilename(option=value, …) 这个是”打开”对话框
  • 一个是:asksaveasfilename(option=value, …) 这个是另存为对话框
  • 另一个是:askdirectory()这个是路径选择对话框

option参数如下:

  • defaultextension = s 默认文件的扩展名
  • filetypes = [(label1, pattern1), (label2, pattern2), …] 设置文件类型下拉菜单里的的选项
  • initialdir = D 对话框中默认的路径
  • initialfile = F 对话框中初始化显示的文件名
  • parent = W 父对话框(由哪个窗口弹出就在哪个上端)
  • title = T 弹出对话框的标题

如果选中文件的话,确认后会显示文件的完整路径,否则单击取消的话会返回空字符串

示例

#coding=UTF-8    
import Tkinter, Tkconstants, tkFileDialog  
class TkFileDialogExample(Tkinter.Frame):  

    def __init__(self, root):  
        Tkinter.Frame.__init__(self, root)  
        # options for buttons  
        button_opt = {'fill': Tkconstants.BOTH, 'padx': 5, 'pady': 5}  

        # define buttons  
        Tkinter.Button(self, text='askopenfile', command=self.askopenfile).pack(**button_opt)  
        Tkinter.Button(self, text='askopenfilename', command=self.askopenfilename).pack(**button_opt)  
        Tkinter.Button(self, text='asksaveasfile', command=self.asksaveasfile).pack(**button_opt)  
        Tkinter.Button(self, text='asksaveasfilename', command=self.asksaveasfilename).pack(**button_opt)  
        Tkinter.Button(self, text='askdirectory', command=self.askdirectory).pack(**button_opt)  

        # define options for opening or saving a file  
        self.file_opt = options = {}  
        options['defaultextension'] = '.txt'  
        options['filetypes'] = [('all files', '.*'), ('text files', '.txt')]  
        options['initialdir'] = 'C:\\'  
        options['initialfile'] = 'myfile.txt'  
        options['parent'] = root  
        options['title'] = 'This is a title'  

        # This is only available on the Macintosh, and only when Navigation Services are installed.  
        #options['message'] = 'message'  

        # if you use the multiple file version of the module functions this option is set automatically.  
        #options['multiple'] = 1  

        # defining options for opening a directory  
        self.dir_opt = options = {}  
        options['initialdir'] = 'C:\\'  
        options['mustexist'] = False  
        options['parent'] = root  
        options['title'] = 'This is a title'  

    def askopenfile(self):  

        """Returns an opened file in read mode."""  

        return tkFileDialog.askopenfile(mode='r', **self.file_opt)  

    def askopenfilename(self):  

        """Returns an opened file in read mode. 
        This time the dialog just returns a filename and the file is opened by your own code. 
        """  

        # get filename  
        filename = tkFileDialog.askopenfilename(**self.file_opt)  

        # open file on your own  
        if filename:  
            return open(filename, 'r')  

    def asksaveasfile(self):  

        """Returns an opened file in write mode."""  

        return tkFileDialog.asksaveasfile(mode='w', **self.file_opt)  

    def asksaveasfilename(self):  

        """Returns an opened file in write mode. 
        This time the dialog just returns a filename and the file is opened by your own code. 
        """  

        # get filename  
        filename = tkFileDialog.asksaveasfilename(**self.file_opt)  

        # open file on your own  
        if filename:  
            return open(filename, 'w')  

    def askdirectory(self):  

        """Returns a selected directoryname."""  

        return tkFileDialog.askdirectory(**self.dir_opt)  

if __name__ == '__main__':  
    root = Tkinter.Tk()  
    TkFileDialogExample(root).pack()  
    root.mainloop()

ImportError: No module named 'tkFileDialog'问题

原因

python2和pyton3的版本问题。python3之后的版本自带有tkinter.

验证

  • import _tkinter
  • import tkinter
  • tkinter._test()

在python3中输入以上命令进行验证。

解决方法

Python2中应该写成  

from tkFileDialog import askdirectory

python3中应该写成  

from tkinter.filedialog import askdirectory

tkColorChooser ------------>tkinter.colorchooser
tkCommonDialog --------------->tkinter.commondialog   

其他的可以类推。


Tags in this post...

Python 相关文章推荐
Python实现删除Android工程中的冗余字符串
Jan 19 Python
Windows下Python使用Pandas模块操作Excel文件的教程
May 31 Python
Python实现扩展内置类型的方法分析
Oct 16 Python
python破解zip加密文件的方法
May 31 Python
分享vim python缩进等一些配置
Jul 02 Python
python3.5绘制随机漫步图
Aug 27 Python
python3.6下Numpy库下载与安装图文教程
Apr 02 Python
pip 安装库比较慢的解决方法(国内镜像)
Oct 06 Python
python3安装OCR识别库tesserocr过程图解
Apr 02 Python
Python requests及aiohttp速度对比代码实例
Jul 16 Python
如何在Python3中使用telnetlib模块连接网络设备
Sep 21 Python
python 实现数据库中数据添加、查询与更新的示例代码
Dec 07 Python
Python Flask实现进度条
May 11 #Python
Python PIL按比例裁剪图片
May 11 #Python
python 学习GCN图卷积神经网络
May 11 #Python
Python+Pillow+Pytesseract实现验证码识别
May 11 #Python
Python 绘制多因子柱状图
PyCharm 配置SSH和SFTP连接远程服务器
May 11 #Python
Python 文字识别
May 11 #Python
You might like
配置PHP使之能同时支持GIF和JPEG
2006/10/09 PHP
php + nginx项目中的权限详解
2017/05/23 PHP
js宝典学习笔记(上)
2007/01/10 Javascript
jquery的Tooltip插件 qtip使用详细说明
2010/09/08 Javascript
javascript event 事件解析
2011/01/31 Javascript
JavaScript中的null和undefined解析
2012/04/14 Javascript
jQuery解析XML文件同时动态增加js文件的方法
2015/06/01 Javascript
jquery实现简单的二级导航下拉菜单效果
2015/09/07 Javascript
浅谈JS之iframe中的窗口
2016/09/13 Javascript
使用jQuery操作DOM的方法小结
2017/02/27 Javascript
JavaScript反射与依赖注入实例详解
2018/05/29 Javascript
小程序:授权、登录、session_key、unionId的详解
2019/05/15 Javascript
vue2.x数组劫持原理的实现
2020/04/19 Javascript
微信小程序实现底部弹出模态框
2020/11/18 Javascript
[48:26]VGJ.S vs infamous Supermajor 败者组 BO3 第二场 6.4
2018/06/05 DOTA
Python 模块EasyGui详细介绍
2017/02/19 Python
python 读取.csv文件数据到数组(矩阵)的实例讲解
2018/06/14 Python
python列表list保留顺序去重的实例
2018/12/14 Python
对django views中 request, response的常用操作详解
2019/07/17 Python
python自动发微信监控报警
2019/09/06 Python
基于Python和PyYAML读取yaml配置文件数据
2020/01/13 Python
使用python处理题库表格并转化为word形式的实现
2020/04/14 Python
Python 如何批量更新已安装的库
2020/05/26 Python
解决python打开https出现certificate verify failed的问题
2020/09/03 Python
Python try except else使用详解
2021/01/12 Python
纯CSS3编写的的精美动画进度条(无flash/无图像/无脚本/附源码)
2013/01/07 HTML / CSS
html5 application cache遇到的严重问题
2012/12/26 HTML / CSS
HTML5各种头部meta标签的功能(推荐)
2017/03/13 HTML / CSS
澳大利亚购买健身器材网站:Gym Direct
2019/12/19 全球购物
学校食堂采购员岗位职责
2013/12/05 职场文书
工厂会计员职责
2014/02/06 职场文书
师范大学生求职信
2014/06/13 职场文书
关于运动会广播稿200字
2014/10/08 职场文书
运动会报道稿大全
2015/07/23 职场文书
分析Java中Map的遍历性能问题
2021/06/26 Java/Android
Golang map映射的用法
2022/04/22 Golang