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 相关文章推荐
pip 错误unused-command-line-argument-hard-error-in-future解决办法
Jun 01 Python
python实现画一颗树和一片森林
Jun 25 Python
Pytorch抽取网络层的Feature Map(Vgg)实例
Aug 20 Python
django drf框架自带的路由及最简化的视图
Sep 10 Python
python程序中的线程操作 concurrent模块使用详解
Sep 23 Python
python GUI库图形界面开发之PyQt5布局控件QGridLayout详细使用方法与实例
Mar 06 Python
如何在django中运行scrapy框架
Apr 22 Python
详解pytorch tensor和ndarray转换相关总结
Sep 03 Python
Python HTMLTestRunner如何下载生成报告
Sep 04 Python
解决numpy数组互换两行及赋值的问题
Apr 17 Python
python中的None与NULL用法说明
May 25 Python
Python基础数据类型tuple元组的概念与用法
Aug 02 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
DOTA2 玩家自创拉野攻略 特色英雄快速成长篇
2020/04/20 DOTA
自动跳转中英文页面
2006/10/09 PHP
屏蔽机器人从你的网站搜取email地址的php代码
2012/11/14 PHP
php安装xdebug/php安装pear/phpunit详解步骤(图)
2013/12/22 PHP
easyui的tabs update正确用法分享
2014/03/21 PHP
利用php-cli和任务计划实现订单同步功能的方法
2017/05/03 PHP
PHP levenshtein()函数用法讲解
2019/03/08 PHP
php设计模式之策略模式应用案例详解
2019/06/17 PHP
不常用但很实用的PHP预定义变量分析
2019/06/25 PHP
基于JavaScript 数据类型之Boolean类型分析介绍
2013/04/19 Javascript
纯JS实现动态时间显示代码
2014/02/08 Javascript
JS JQUERY实现滚动条自动滚到底的方法
2015/01/09 Javascript
jquery实现的3D旋转木马特效代码分享
2015/08/25 Javascript
jQuery获取checkboxlist的value值的方法
2015/09/27 Javascript
js获取元素的外链样式的简单实现方法
2016/06/06 Javascript
javaScript语法总结
2016/11/25 Javascript
javascript中call,apply,bind函数用法示例
2016/12/19 Javascript
JQuery模拟实现网页中自定义鼠标右键菜单功能
2018/11/14 jQuery
vue路由 遍历生成复数router-link的例子
2019/10/30 Javascript
python实现给字典添加条目的方法
2014/09/25 Python
Python 备份程序代码实现
2017/03/06 Python
windows环境下tensorflow安装过程详解
2018/03/30 Python
对pandas的算术运算和数据对齐实例详解
2018/12/22 Python
python 多个参数不为空校验方法
2019/02/14 Python
Python OpenCV利用笔记本摄像头实现人脸检测
2020/08/20 Python
英国最大的奢侈品零售网络商城:Flannels
2016/09/16 全球购物
服务员自我评价
2014/01/25 职场文书
护理专业学生职业生涯规划范文
2014/03/11 职场文书
2014财产信托协议书范本
2014/11/18 职场文书
任命书怎么写
2015/03/02 职场文书
出国留学英文自荐信
2015/03/25 职场文书
2015年社区综治宣传月活动总结
2015/03/25 职场文书
2016年“12.3”国际残疾人日活动总结
2016/04/01 职场文书
责任书格式
2019/04/18 职场文书
JS实现扫雷项目总结
2021/05/19 Javascript
Docker部署Mysql8的实现步骤
2022/07/07 Servers