Python中使用tkFileDialog实现文件选择、保存和路径选择

 更新时间:2022年05月20日 11:42:31   作者:blingbling_110  
这篇文章主要介绍了Python中使用tkFileDialog实现文件选择、保存和路径选择,具有很好的参考价值,希望对大家有所帮助。如有错误或未考虑完全的地方,望不吝赐教

使用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   

其他的可以类推。

以上为个人经验,希望能给大家一个参考,也希望大家多多支持脚本之家。

相关文章

  • python3.7将代码打包成exe程序并添加图标的方法

    python3.7将代码打包成exe程序并添加图标的方法

    这篇文章主要介绍了python3.7将代码打包成exe程序并添加图标的方法,本文给大家介绍的非常详细,具有一定的参考借鉴价值 ,需要的朋友可以参考下
    2019-10-10
  • 详解python之协程gevent模块

    详解python之协程gevent模块

    这篇文章主要介绍了详解python之协程gevent模块,小编觉得挺不错的,现在分享给大家,也给大家做个参考。一起跟随小编过来看看吧
    2018-06-06
  • 使用Python实现微信拍一拍功能的思路代码

    使用Python实现微信拍一拍功能的思路代码

    这篇文章主要介绍了使用Python实现微信“拍一拍”的思路代码,,本文通过示例代码给大家介绍的非常详细,对大家的学习或工作具有一定的参考借鉴价值,需要的朋友可以参考下
    2020-07-07
  • 关于python爬虫的原理解析

    关于python爬虫的原理解析

    这篇文章主要介绍了python爬虫原理,今天我们要向大家详细解说python爬虫原理,什么是python爬虫,python爬虫工作的基本流程是什么等内容,希望对这正在进行python爬虫学习的同学有所帮助
    2023-07-07
  • 关于matplotlib及相关cmap参数的取值方式

    关于matplotlib及相关cmap参数的取值方式

    这篇文章主要介绍了关于matplotlib及相关cmap参数的取值方式,具有很好的参考价值,希望对大家有所帮助。如有错误或未考虑完全的地方,望不吝赐教
    2022-11-11
  • python实现提取COCO,VOC数据集中特定的类

    python实现提取COCO,VOC数据集中特定的类

    这篇文章主要介绍了python实现提取COCO,VOC数据集中特定的类,具有很好的参考价值,希望对大家有所帮助。一起跟随小编过来看看吧
    2020-03-03
  • pycharm没有找到manage repositories按钮的解决办法

    pycharm没有找到manage repositories按钮的解决办法

    这篇文章主要给大家介绍了关于pycharm没有找到manage repositories按钮的解决办法,pycharm是用来写python的可视化代码软件,文中通过图文介绍的非常详细,需要的朋友可以参考下
    2023-07-07
  • PyInstaller将Python脚本打包为.exe可执行文件的步骤详解

    PyInstaller将Python脚本打包为.exe可执行文件的步骤详解

    Python是一门强大而灵活的编程语言,为了方便共享和部署,我们可以将 Python 脚本打包为可执行文件(.exe),这样其他用户就无需安装 Python环境,直接运行可执行文件即可,本文将介绍如何使用PyInstaller 工具实现这一目标,需要的朋友可以参考下
    2023-12-12
  • 如何使用Python VTK绘制线条

    如何使用Python VTK绘制线条

    这篇文章主要介绍了如何使用Python-VTK绘制线条,主要绘制直线和曲线,下面文章详细实现过程需要的小伙伴可以参考一下
    2022-04-04
  • Python插件机制实现详解

    Python插件机制实现详解

    这篇文章主要介绍了Python插件机制实现详解,具有很好的参考价值,希望对大家有所帮助。一起跟随小编过来看看吧
    2020-05-05

最新评论