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的列表中利用remove()方法删除元素的教程
May 21 Python
python链接Oracle数据库的方法
Jun 28 Python
基于Python实现通过微信搜索功能查看谁把你删除了
Jan 27 Python
Python脚本简单实现打开默认浏览器登录人人和打开QQ的方法
Apr 12 Python
python strip() 函数和 split() 函数的详解及实例
Feb 03 Python
python打包压缩、读取指定目录下的指定类型文件
Apr 12 Python
python脚本监控Tomcat服务器的方法
Jul 06 Python
Django Rest framework频率原理与限制
Jul 26 Python
浅谈django2.0 ForeignKey参数的变化
Aug 06 Python
tensorflow实现打印ckpt模型保存下的变量名称及变量值
Jan 04 Python
使用jupyter notebook运行python和R的步骤
Aug 13 Python
python音频处理的示例详解
Dec 23 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 超链接 抓取实现代码
2009/06/29 PHP
php 使用ActiveMQ发送消息,与处理消息操作示例
2020/02/23 PHP
如果文字过长,则将过长的部分变成省略号显示
2006/06/26 Javascript
解析javascript 实用函数的使用详解
2013/05/10 Javascript
jquery实现不同大小浏览器使用不同的css样式表的方法
2014/04/02 Javascript
javascript实现多级联动下拉菜单的方法
2015/02/06 Javascript
js禁止Backspace键使浏览器后退的实现方法
2017/09/01 Javascript
利用JS实现scroll自定义滚动效果详解
2017/10/17 Javascript
一种angular的方法级的缓存注解(装饰器)
2018/03/13 Javascript
15分钟深入了解JS继承分类、原理与用法
2019/01/19 Javascript
Bootstrap实现省市区三级联动(亲测可用)
2019/07/26 Javascript
JavaScript如何借用构造函数继承
2019/11/06 Javascript
uniapp与webview之间的相互传值的实现
2020/06/29 Javascript
JavaScript实现多层颜色选项卡嵌套
2020/09/21 Javascript
Python实现的彩票机选器实例
2015/06/17 Python
Django中更新多个对象数据与删除对象的方法
2015/07/17 Python
Python中join函数简单代码示例
2018/01/09 Python
Python3实现购物车功能
2018/04/18 Python
Python装饰器的执行过程实例分析
2018/06/04 Python
python3中函数参数的四种简单用法
2018/07/09 Python
python的scikit-learn将特征转成one-hot特征的方法
2018/07/10 Python
在Python中通过getattr获取对象引用的方法
2019/01/21 Python
java中的控制结构(if,循环)详解
2019/06/26 Python
python opencv 批量改变图片的尺寸大小的方法
2019/06/28 Python
Python+Opencv实现把图片、视频互转的示例
2020/12/17 Python
用HTML5.0制作网页的教程
2010/05/30 HTML / CSS
Shoes For Crews法国官网:美国领先的防滑鞋设计和制造商
2018/01/01 全球购物
销售工作人员的自我评价分享
2013/11/10 职场文书
开办大学饮食联盟创业计划书
2014/01/29 职场文书
工程承包协议书
2014/04/22 职场文书
服务标语大全
2014/06/18 职场文书
政风行风整改方案
2014/10/25 职场文书
贵阳市党的群众路线教育实践活动党(工)委领导班子整改方案
2014/10/26 职场文书
投资意向协议书
2015/01/29 职场文书
合同补充协议书
2016/03/24 职场文书
台式电脑蓝牙适配器怎么安装?台式电脑蓝牙适配器安装教程
2022/04/08 数码科技