Table of Contents
Preface
1.Methods in tkinter.filedialog
2.Test cases
2.1 Create tkinter window
2.1.1 Import module
2.1.2 Create a tkinter window that can be hidden
2.2 Call the functions in tkinter.filedialog to perform graphical file operations
Foreword
For a productivity software, graphical file access operations are often a necessary function. Through graphical file access operations, users can open or save files conveniently and quickly.
Taking Visual Studio 2022 as an example, we will see the following button control in its top navigation bar.
Click “Open” or “New” in the file button to bring up the system’s own file explorer. Users can perform comfortable and fast file access operations in the system’s graphical file manager instead of in the system’s graphical file manager. Perform more “abstract” and cumbersome operations on the command line.
So, if we use python for programming, how do we achieve the above functions? Next, the author will introduce in detail the protagonist of our article—tkinter.filedialog. Using the tkinker graphical programming library, we can achieve all this in a very simple way.
Method in 1.tkinter.filedialog
The following are some of the more practical graphical file resource manager scheduling methods in tkinter.filedialog
tkinter.filedialog.asksaveasfilename()#Return the file name to be saved
tkinter.filedialog.asksaveasfile()#Create file and return file stream object
tkinter.filedialog.askopenfilename()#Return the file name to be opened
tkinter.filedialog.askopenfile()#Returns the file stream object to be opened
tkinter.filedialog.askdirectory()#Return directory name
tkinter.filedialog.askopenfilenames()#can return multiple file names
tkinter.filedialog.askopenfiles()#Return multiple file stream objects
The parameters of these functions are roughly the same. The author has organized the more commonly used parameters into the following table.
parameter name |
Function |
defaultextension |
Default file extension |
title |
Determine the title of the graphical window |
initialdir |
The default path in the dialog box |
initialfile |
The file name initially displayed in the dialog box |
parent |
tkinter parent dialog box (whichever window pops up will be at the top) |
filetypes |
[(label1, pattern1), (label2, pattern2), …] Set the optional file types in the file type drop-down menu |
by
tkinter.filedialog.asksaveasfilename(title=”save your file”, initialdir=”save_file”, initialfile = “test”,filetypes=[[“Text file”,”.txt .docx .doc”],[“Excel”, “.xls .xlsx”]], defaultextension=”.tif”)
For example, the following effect will be achieved:
2. Test case
2.1 Create tkinter window
2.1.1 Import module
import tkinter as tk import tkinter.filedialog import pyautogui #Improve picture quality import os
Among them, pyautogui can be used to increase the dpi of the system file explorer and enhance visual effects. If this module is not referenced, the interface will be slightly blurry.
2.1.2 Create a tkinter window that can be hidden
Hidden windows can be perfectly integrated with other graphical interfaces. If we use pygame to make a game and want to save the game at a certain node, if we call tkinter without hiding the tkinter interface like in this article, a blank interface will appear out of thin air. , resulting in a sense of fragmentation. Of course, this is just the approach recommended by the author, and readers can make their own choices.
root = tk.Tk() root.withdraw()
2.2 Call the functions in tkinter.filedialog for graphical file operations
Next, just call the method described in Section 1. The author has written a test case to facilitate readers to quickly test and learn. The complete code is as follows.
''' author ZevieZ more interesting contents @https://blog.csdn.net/weixin_50233916?type=blog ''' import tkinter.filedialog importpyautogui import tkinter as tk import os #The relative path of the test folder (the path relative to the location of this script file), used to test the tkinker file explorer scheduling function SAVE_FILES_PATH = "save_file" def save_file(title="save your file", initialdir="save_file", initialfile = "test",filetypes=[["Text file",".txt .docx .doc"],["Excel", ".xls .xlsx"]], defaultextension=".tif"): ''' save document ''' #Get the desired file saving path from the system's file explorer get_save_path = tkinter.filedialog.asksaveasfilename(title = title, initialdir = initialdir, initialfile = initialfile, filetypes = filetypes, defaultextension = defaultextension) print("The obtained file saving path is -> ",get_save_path) #Subsequent file saving operation, python IO stream, here is a txt file as an example as a demonstration text = input("Enter the content you want to save:") #The text you want to write and save newfile = open(get_save_path,"w + ",encoding="utf-8") newfile.write(text) print("Save successfully") print() newfile.close() pass def open_file(title="select your file"): ''' save document ''' #Get the desired file saving path from the system's file explorer get_open_path = tkinter.filedialog.askopenfilename(title = title) print("The selected file path is -> ",get_open_path) #Subsequent file saving operation, python IO stream, here is a txt file as an example as a demonstration newfile = open(get_open_path,"r",encoding="utf-8") pcontent = newfile.read() print("The content of this file is->\ ",pcontent) print() newfile.close() pass def test_func(): ''' Test each practical tkinker file explorer deployment function in turn ''' print("asksaveasfilename") path =tkinter.filedialog.asksaveasfilename()#return file name print(path) print("asksaveasfile") path =tkinter.filedialog.asksaveasfile()# will create the file print(path) print("askopenfilename") path =tkinter.filedialog.askopenfilename()#Return file name print(path) print("askopenfile") path =tkinter.filedialog.askopenfile()#Return file stream object print(path) print("askdirectory") path =tkinter.filedialog.askdirectory()#Return directory name print(path) print("askopenfilenames") path =tkinter.filedialog.askopenfilenames()#can return multiple file names print(path) print("askopenfiles") path =tkinter.filedialog.askopenfiles()#Multiple file stream objects print(path) if __name__ == "__main__": #Instantiate the tkinker window root = tk.Tk() root.withdraw() rewrite_menu = True #Create a test folder if (os.path.exists(SAVE_FILES_PATH) == False): os.mkdir(SAVE_FILES_PATH) while(1): #printmenu if rewrite_menu: print("----------------------------------") print("1-> Save file (test asksaveasfilename)") print("2->Open file (test askopenfilename)") print("3->Test each practical tkinker file explorer mobilization function in turn") print("4->Exit") order = input() #Get input instructions #processing instructions rewrite_menu = True if (order == "1"): save_file() elif (order == "2"): open_file() elif (order == "3"): test_func() elif (order == "4"): break else: print("Input error\ ") rewrite_menu = False
After running, you can see a folder named save_file in the directory, which can store files saved by users during the test process.
Readers can select different test contents according to the menu prompts and see the output results in the command line. Of course, you can also check the status of the file in save_file for verification.
The knowledge points of the article match the official knowledge files, and you can further learn relevant knowledge. Python entry skill tree Home page Overview 358,136 people are learning the system