tkinter.filedialog 引用askdirectory库来获取文件夹路径
首先,导入库
import tkinter as tk
from tkinter.filedialog import askdirectory
定义一个返回路径的方法,方便调用:
###读取路径并返回路径到文本框
def selectPath():
path_ = askdirectory()
path.set(path_)
定义按纽来触发获取文件夹路径的事件,定义文本框来显示选取的本地文件夹路径
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=selectPath).grid(row=0, column=2)
执行结果:
本文代码:
import tkinter as tk
from tkinter.filedialog import askdirectory
###读取路径并返回路径到文本框
def selectPath():
path_ = askdirectory()
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=selectPath).grid(row=0, column=2)
root.mainloop()