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之不要红头文件(1)
Sep 28 Python
使用优化器来提升Python程序的执行效率的教程
Apr 02 Python
Python中统计函数运行耗时的方法
May 05 Python
python显示生日是星期几的方法
May 27 Python
tensorflow构建BP神经网络的方法
Mar 12 Python
python中文编码与json中文输出问题详解
Aug 24 Python
python实现邮件自动发送
Aug 10 Python
python自动化测试无法启动谷歌浏览器问题
Oct 10 Python
python使用信号量动态更新配置文件的操作
Apr 01 Python
python 安装库几种方法之cmd,anaconda,pycharm详解
Apr 08 Python
Python全局变量与global关键字常见错误解决方案
Oct 05 Python
python 从list中随机取值的方法
Nov 16 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
怎么使 Mysql 数据同步
2006/10/09 PHP
php多个字符串替换成同一个的解决方法
2013/06/18 PHP
PHP函数nl2br()与自定义函数nl2p()换行用法分析
2016/04/02 PHP
php生成验证码,缩略图及水印图的类分享
2016/04/07 PHP
js 数值转换为3位逗号分隔的示例代码
2014/02/19 Javascript
JS将光标聚焦在文本最后的实现代码
2014/03/28 Javascript
JavaScript中的object转换函数toString()与valueOf()介绍
2014/12/31 Javascript
JQuery工具函数汇总
2015/06/15 Javascript
JavaScript职责链模式概述
2016/09/17 Javascript
8 行 Node.js 代码实现代理服务器
2016/12/05 Javascript
vue快捷键与基础指令详解
2017/06/01 Javascript
jQuery选择器之表单元素选择器详解
2017/09/19 jQuery
基于Vue组件化的日期联动选择器功能的实现代码
2018/11/30 Javascript
vue 集成 vis-network 实现网络拓扑图的方法
2019/08/07 Javascript
微信小程序点击按钮动态切换input的disabled禁用/启用状态功能
2020/03/07 Javascript
Vue的data、computed、watch源码浅谈
2020/04/04 Javascript
详解vue-router的Import异步加载模块问题的解决方案
2020/05/13 Javascript
Vue-router中hash模式与history模式的区别详解
2020/12/15 Vue.js
[38:23]2014 DOTA2国际邀请赛中国区预选赛 5 23 CIS VS LGD第一场
2014/05/24 DOTA
[00:37]DOTA2上海特级锦标赛 OG战队宣传片
2016/03/03 DOTA
[03:10]超级美酒第四天 fy拉比克秀 大合集
2018/06/05 DOTA
Python字符串、元组、列表、字典互相转换的方法
2016/01/23 Python
Python正则抓取网易新闻的方法示例
2017/04/21 Python
详解Python的循环结构知识点
2019/05/20 Python
python3连接mysql获取ansible动态inventory脚本
2020/01/19 Python
解决pycharm每次打开项目都需要配置解释器和安装库问题
2020/02/26 Python
基于python requests selenium爬取excel vba过程解析
2020/08/12 Python
美国购买韩国护肤和美容产品网站:Althea Korea
2020/11/16 全球购物
大学校园毕业自我鉴定
2014/01/15 职场文书
个人三严三实对照检查材料
2014/09/25 职场文书
学校党员个人问题整改措施思想汇报
2014/10/08 职场文书
酒店办公室主任岗位职责
2015/04/01 职场文书
女性健康知识讲座通知
2015/04/23 职场文书
2016年寒假政治学习心得体会
2015/10/09 职场文书
python 定义函数 返回值只取其中一个的实现
2021/05/21 Python
Redis性能监控的实现
2021/07/09 Redis