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编程实现语音控制电脑
Apr 01 Python
python实现的解析crontab配置文件代码
Jun 30 Python
解析Python中的异常处理
Apr 28 Python
在Python程序中进行文件读取和写入操作的教程
Apr 28 Python
初步剖析C语言编程中的结构体
Jan 16 Python
详解python调度框架APScheduler使用
Mar 28 Python
Python微信库:itchat的用法详解
Aug 14 Python
python 正确保留多位小数的实例
Jul 16 Python
python爬取酷狗音乐排行榜
Feb 20 Python
pytorch实现用CNN和LSTM对文本进行分类方式
Jan 08 Python
pycharm 添加解释器的方法步骤
Aug 31 Python
python从ftp获取文件并下载到本地
Dec 05 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+mysql 采用ajax技术的 省 市 地 3级联动无刷新菜单 源码
2006/12/16 PHP
用PHP写的MySQL数据库用户认证系统代码
2007/03/22 PHP
php分页函数示例代码分享
2014/02/24 PHP
CodeIgniter框架实现的整合Smarty引擎DEMO示例
2019/03/28 PHP
showModalDialog 和 showModelessDialog
2007/01/22 Javascript
JQuery小知识
2010/10/15 Javascript
jquery中的 $("#jb51")与document.getElementById("jb51") 的区别
2011/07/26 Javascript
jquery删除数据记录时的弹出提示效果
2014/05/06 Javascript
纯javascript实现分页(两种方法)
2015/08/26 Javascript
微信QQ的二维码登录原理js代码解析
2016/06/23 Javascript
关于laydate.js加载laydate.css路径错误问题解决
2017/12/27 Javascript
Taro集成Redux快速上手的方法示例
2018/06/21 Javascript
浅谈Vue数据响应
2018/11/05 Javascript
createObjectURL方法实现本地图片预览
2019/09/30 Javascript
JS实现烟花爆炸效果
2020/03/10 Javascript
JavaScript实现留言板案例
2020/03/17 Javascript
微信小程序实现单个或多个倒计时功能
2020/11/01 Javascript
React服务端渲染原理解析与实践
2021/03/04 Javascript
全面了解Python环境配置及项目建立
2016/06/30 Python
Python基于Pymssql模块实现连接SQL Server数据库的方法详解
2017/07/20 Python
python+matplotlib演示电偶极子实例代码
2018/01/12 Python
python查找重复图片并删除(图片去重)
2019/07/16 Python
Pycharm+django2.2+python3.6+MySQL实现简单的考试报名系统
2019/09/05 Python
Python 最强编辑器详细使用指南(PyCharm )
2019/09/16 Python
Python使用扩展库pywin32实现批量文档打印实例
2020/04/09 Python
PyCharm最新激活码(2020/10/27全网最新)
2020/10/27 Python
CSS3 简写animation
2012/05/10 HTML / CSS
基于MUI框架使用HTML5实现的二维码扫描功能
2018/03/01 HTML / CSS
英国折扣零售连锁店:QD Stores
2018/12/08 全球购物
工商治理实习生的自我评价
2014/01/15 职场文书
博士毕业生自我鉴定范文
2014/04/13 职场文书
给老婆的保证书怎么写
2015/05/08 职场文书
安全事故隐患排查治理制度
2015/08/05 职场文书
2016年小学生新年寄语
2015/08/18 职场文书
七年级思品教学反思
2016/02/20 职场文书
Vue的列表之渲染,排序,过滤详解
2022/02/24 Vue.js