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随机生成彩票号码的方法
Mar 05 Python
Python的Django框架可适配的各种数据库介绍
Jul 15 Python
对python requests的content和text方法的区别详解
Oct 11 Python
Django接收自定义http header过程详解
Aug 23 Python
python英语单词测试小程序代码实例
Sep 09 Python
pytorch制作自己的LMDB数据操作示例
Dec 18 Python
Python selenium爬取微博数据代码实例
May 22 Python
python:HDF和CSV存储优劣对比分析
Jun 08 Python
python要安装在哪个盘
Jun 15 Python
python语言中有算法吗
Jun 16 Python
python对批量WAV音频进行等长分割的方法实现
Sep 25 Python
Appium+Python实现简单的自动化登录测试的实现
Jan 26 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
Windows下PHP5和Apache的安装与配置
2006/09/05 PHP
数据库的日期格式转换
2006/10/09 PHP
实用函数10
2007/11/08 PHP
PHP 身份证号验证函数
2009/05/07 PHP
zf框架的db类select查询器join链表使用示例(zend框架)
2014/03/14 PHP
很多人都是用下面的js刷新站IP和PV
2008/09/05 Javascript
JavaScript极简入门教程(一):基础篇
2014/10/25 Javascript
javascript中定义类的方法详解
2015/02/10 Javascript
JS实现的表格行鼠标点击高亮效果代码
2015/11/27 Javascript
微信小程序 WXML、WXSS 和JS介绍及详解
2016/10/08 Javascript
JS中this上下文对象使用方式
2016/10/09 Javascript
BootStrap实现带有增删改查功能的表格(DEMO详解)
2016/10/26 Javascript
用户管理的设计_jquery的ajax实现二级联动效果
2017/07/13 jQuery
Angularjs中数据绑定的实例详解
2017/08/25 Javascript
JavaScript变量提升和严格模式实例分析
2019/01/27 Javascript
vue从一个页面跳转到另一个页面并携带参数的解决方法
2019/08/12 Javascript
vue中实现上传文件给后台实例详解
2019/08/22 Javascript
vue全屏事件开发详解
2020/06/17 Javascript
Vue父组件监听子组件生命周期
2020/09/03 Javascript
[51:17]Mineski vs Secret 2019国际邀请赛淘汰赛 败者组 BO3 第一场 8.22
2019/09/05 DOTA
python格式化字符串实例总结
2014/09/28 Python
Python中的__SLOTS__属性使用示例
2015/02/18 Python
举例讲解Python中metaclass元类的创建与使用
2016/06/30 Python
python 全文检索引擎详解
2017/04/25 Python
python实现日志按天分割
2019/07/22 Python
python 队列基本定义与使用方法【初始化、赋值、判断等】
2019/10/24 Python
好药师网上药店:安全合法的网上药品零售药房
2017/02/15 全球购物
美国伊甸园兄弟种子公司:Eden Brothers
2018/07/01 全球购物
西班牙购买行李箱和背包网站:Maletas Greenwich
2019/10/08 全球购物
宿舍违规用电检讨书
2014/02/16 职场文书
餐饮服务食品安全责任书
2014/07/25 职场文书
旷课检讨书500字
2014/10/14 职场文书
小学生禁毒教育心得体会
2016/01/15 职场文书
高三语文教学反思
2016/02/16 职场文书
创业计划书之DIY自助厨房
2019/09/06 职场文书
自定义函数实现单词排序并运用于PostgreSQL(实现代码)
2021/04/22 PostgreSQL