about python Of tkinter For the library , If you need to pop up a file selection box , We need to introduce tkinter.filedialog package , Let the user intuitively select one or more files or save files and other operations .
Common file selection dialog functions are
The first is to open a file. The dialog function we will use is askopenfilename()
from tkinter import *
import tkinter.filedialog
root = Tk()
def xz():
filename = tkinter.filedialog.askopenfilename()
if filename != '':
lb.config(text = " The file you selected is :"+filename);
else:
lb.config(text = " You have not selected any files ");
lb = Label(root,text = '')
lb.pack()
btn = Button(root,text=" The file selection dialog box will pop up ",command=xz)
btn.pack()
root.mainloop()
Before selecting a file :
After selecting the file :
The next step is to select a group of files and display them in the dialog box
from tkinter import *
import tkinter.filedialog
root = Tk()
def xz():
filenames = tkinter.filedialog.askopenfilenames()
if len(filenames) != 0:
string_filename =""
for i in range(0,len(filenames)):
string_filename += str(filenames[i])+"\n"
lb.config(text = " The file you selected is :"+string_filename)
else:
lb.config(text = " You have not selected any files ");
lb = Label(root,text = '')
lb.pack()
btn = Button(root,text=" The file selection dialog box will pop up ",command=xz)
btn.pack()
root.mainloop()
Selecting multiple files is the same as selecting a single file
After selecting multiple files
In the process of writing code, I found that tkinter.filedialog.askopenfilenames() Back to a tuple data type , So I'm going to deal with it first len(tuple) Is it 0, If not, use it for The loop forces it into str(tuple[i]) To string_filename The file name can be displayed in