溫馨提示×

您好,登錄后才能下訂單哦!

密碼登錄×
登錄注冊(cè)×
其他方式登錄
點(diǎn)擊 登錄注冊(cè) 即表示同意《億速云用戶服務(wù)條款》

Python中怎么使用tkFileDialog實(shí)現(xiàn)文件選擇、保存和路徑選擇

發(fā)布時(shí)間:2022-05-20 14:21:57 來(lái)源:億速云 閱讀:784 作者:iii 欄目:開發(fā)技術(shù)

這篇“Python中怎么使用tkFileDialog實(shí)現(xiàn)文件選擇、保存和路徑選擇”文章的知識(shí)點(diǎn)大部分人都不太理解,所以小編給大家總結(jié)了以下內(nèi)容,內(nèi)容詳細(xì),步驟清晰,具有一定的借鑒價(jià)值,希望大家閱讀完這篇文章能有所收獲,下面我們一起來(lái)看看這篇“Python中怎么使用tkFileDialog實(shí)現(xiàn)文件選擇、保存和路徑選擇”文章吧。

使用tkFileDialog實(shí)現(xiàn)文件選擇、保存和路徑選擇

概述

看了下Tkinter的文檔,對(duì)于Pop-up dialog有三類,現(xiàn)在用到的是tkFileDialog

tkFileDialog有三種形式:

  • 一個(gè)是:askopenfilename(option=value, …) 這個(gè)是”打開”對(duì)話框

  • 一個(gè)是:asksaveasfilename(option=value, …) 這個(gè)是另存為對(duì)話框

  • 另一個(gè)是:askdirectory()這個(gè)是路徑選擇對(duì)話框

option參數(shù)如下:

  • defaultextension = s 默認(rèn)文件的擴(kuò)展名

  • filetypes = [(label1, pattern1), (label2, pattern2), …] 設(shè)置文件類型下拉菜單里的的選項(xiàng)

  • initialdir = D 對(duì)話框中默認(rèn)的路徑

  • initialfile = F 對(duì)話框中初始化顯示的文件名

  • parent = W 父對(duì)話框(由哪個(gè)窗口彈出就在哪個(gè)上端)

  • title = T 彈出對(duì)話框的標(biāo)題

如果選中文件的話,確認(rèn)后會(huì)顯示文件的完整路徑,否則單擊取消的話會(huì)返回空字符串

示例

#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.

驗(yàn)證

  • import _tkinter

  • import tkinter

  • tkinter._test()

在python3中輸入以上命令進(jìn)行驗(yàn)證。

解決方法

Python2中應(yīng)該寫成  

from tkFileDialog import askdirectory

python3中應(yīng)該寫成  

from tkinter.filedialog import askdirectory

tkColorChooser ------------>tkinter.colorchooser
tkCommonDialog --------------->tkinter.commondialog   

其他的可以類推。

以上就是關(guān)于“Python中怎么使用tkFileDialog實(shí)現(xiàn)文件選擇、保存和路徑選擇”這篇文章的內(nèi)容,相信大家都有了一定的了解,希望小編分享的內(nèi)容對(duì)大家有幫助,若想了解更多相關(guān)的知識(shí)內(nèi)容,請(qǐng)關(guān)注億速云行業(yè)資訊頻道。

向AI問一下細(xì)節(jié)

免責(zé)聲明:本站發(fā)布的內(nèi)容(圖片、視頻和文字)以原創(chuàng)、轉(zhuǎn)載和分享為主,文章觀點(diǎn)不代表本網(wǎng)站立場(chǎng),如果涉及侵權(quán)請(qǐng)聯(lián)系站長(zhǎng)郵箱:is@yisu.com進(jìn)行舉報(bào),并提供相關(guān)證據(jù),一經(jīng)查實(shí),將立刻刪除涉嫌侵權(quán)內(nèi)容。

AI