首頁 > 軟體

Python中使用tkFileDialog實現檔案選擇、儲存和路徑選擇

2022-05-20 13:12:05

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

其他的可以類推。

以上為個人經驗,希望能給大家一個參考,也希望大家多多支援it145.com。


IT145.com E-mail:sddin#qq.com