欢迎来到代码驿站!

Python代码

当前位置:首页 > 软件编程 > Python代码

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

时间:2022-11-25 10:39:43|栏目:Python代码|点击:

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

其他的可以类推。

上一篇:详解python读写json文件

栏    目:Python代码

下一篇:Python统计词频并绘制图片(附完整代码)

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

本文地址:http://www.codeinn.net/misctech/219825.html

推荐教程

广告投放 | 联系我们 | 版权申明

重要申明:本站所有的文章、图片、评论等,均由网友发表或上传并维护或收集自网络,属个人行为,与本站立场无关。

如果侵犯了您的权利,请与我们联系,我们将在24小时内进行处理、任何非本站因素导致的法律后果,本站均不负任何责任。

联系QQ:914707363 | 邮箱:codeinn#126.com(#换成@)

Copyright © 2020 代码驿站 版权所有