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将阿拉伯数字转换为罗马数字的方法
Jul 10 Python
python计算一个序列的平均值的方法
Jul 11 Python
Python实现求笛卡尔乘积的方法
Sep 16 Python
matplotlib 输出保存指定尺寸的图片方法
May 24 Python
Python Socket编程之多线程聊天室
Jul 28 Python
基于PyQt4和PySide实现输入对话框效果
Feb 27 Python
Django 大文件下载实现过程解析
Aug 01 Python
django 控制页面跳转的例子
Aug 06 Python
Pytest mark使用实例及原理解析
Feb 22 Python
Django用户身份验证完成示例代码
Apr 03 Python
如何在python中实现线性回归
Aug 10 Python
Python如何读写CSV文件
Aug 13 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
自动分页的不完整解决方案
2007/01/12 PHP
使用php来实现网络服务
2009/09/15 PHP
PHP设计模式 注册表模式(多个类的注册)
2012/02/05 PHP
PHP函数分享之curl方式取得数据、模拟登陆、POST数据
2014/06/04 PHP
php服务器的系统详解
2019/10/12 PHP
JavaScript 更严格的相等 [译]
2012/09/20 Javascript
jQuery+JSON+jPlayer实现QQ空间音乐查询功能示例
2013/06/17 Javascript
jquery中通过父级查找进行定位示例
2013/06/28 Javascript
js 采用delete实现继承示例代码
2014/05/20 Javascript
Ext修改GridPanel数据和字体颜色、css属性等
2014/06/13 Javascript
sails框架的学习指南
2014/12/22 Javascript
使用jQuery实现WordPress中的Ctrl+Enter和@评论回复
2016/05/21 Javascript
浅析Ajax语法
2016/12/05 Javascript
从零学习node.js之mysql数据库的操作(五)
2017/02/24 Javascript
通过vue-cli3构建一个SSR应用程序的方法
2018/09/13 Javascript
node.js实现简单的压缩/解压缩功能示例
2019/11/05 Javascript
你可能从未使用过的11+个JavaScript特性(小结)
2020/01/08 Javascript
JavaScript遍历数组的方法代码实例
2020/01/14 Javascript
[03:12]完美世界DOTA2联赛PWL DAY7集锦
2020/11/06 DOTA
Python基于多线程实现抓取数据存入数据库的方法
2018/06/22 Python
python读取文本中的坐标方法
2018/10/14 Python
python写日志文件操作类与应用示例
2019/07/01 Python
Python 、Pycharm、Anaconda三者的区别与联系、安装过程及注意事项
2019/10/11 Python
Python2和Python3中@abstractmethod使用方法
2020/02/04 Python
flask项目集成swagger的方法
2020/12/09 Python
英国鹦鹉店:Parrot Essentials
2018/12/03 全球购物
鉴定评语大全
2014/05/05 职场文书
运动会宣传口号
2014/06/09 职场文书
学校宣传标语
2014/06/18 职场文书
安全例会汇报材料
2014/08/23 职场文书
2016年中秋节慰问信
2015/12/01 职场文书
导游词之京东大峡谷旅游区
2019/10/29 职场文书
使用pytorch实现线性回归
2021/04/11 Python
Windows下redis下载、redis安装及使用教程
2021/06/02 Redis
linux下安装redis图文详细步骤
2021/12/04 Redis
MySQL读取JSON转换的方式
2022/03/18 MySQL