引入tkinter库和askopenfilename, askopenfilenames, askdirectory, asksaveasfilename
import tkinter as tk
from tkinter.filedialog import (askopenfilename, askopenfilenames, askdirectory, asksaveasfilename)
其中askopenfilename (这个是”打开”对话框)用来获取文件路径和名称,askopenfilenames获取多个文件, askdirectory获取文件夹路径 (上文有讲到),asksaveasfilename (这个是另存为对话框)
然后选择文件,并返回路径和文件名
###读取文件并返回文件路径和文件名到文本框
def selectFile():
path_ = askopenfilename()
path.set(path_)
输出结果:
代码:
import tkinter as tk
from tkinter.filedialog import (askopenfilename, askopenfilenames, askdirectory, asksaveasfilename)
###读取文件并返回文件路径和文件名到文本框
def selectFile():
path_ = askopenfilename()
path.set(path_)
root = tk.Tk()
path = tk.StringVar()
tk.Label(root, text="目标文件:").grid(row=0, column=0)
tk.Entry(root, textvariable=path).grid(row=0, column=1)
tk.Button(root, text="文件选择", command=selectFile).grid(row=0, column=2)
root.mainloop()