import tkinter as tk
from tkinter import filedialog
def open_file():
# 弹出文件选择对话框并获取用户选择的文件路径
file_path = filedialog.askopenfilename()
if file_path:
print("Selected file:", file_path)
def save_file():
# 弹出文件保存对话框并获取用户选择的保存路径
file_path = filedialog.asksaveasfilename()
if file_path:
print("Selected save path:", file_path)
def open_multiple_files():
# 弹出文件选择对话框并获取用户选择的多个文件路径
file_paths = filedialog.askopenfilenames()
if file_paths:
print("Selected files:", file_paths)
def choose_directory():
# 弹出目录选择对话框并获取用户选择的目录路径
directory_path = filedialog.askdirectory()
if directory_path:
print("Selected directory:", directory_path)
# 创建主窗口
root = tk.Tk()
root.title("File Dialog Example")
# 创建框架以容纳按钮,并设置左对齐
frame = tk.Frame(root)
frame.pack(padx=10, pady=10, anchor="w")
# 创建按钮并绑定事件,每个按钮调用相应的函数
btn_open_file = tk.Button(frame, text="Open File", command=open_file, width=20)
btn_open_file.pack(pady=5, anchor="w")
btn_save_file = tk.Button(frame, text="Save File", command=save_file, width=20)
btn_save_file.pack(pady=5, anchor="w")
btn_open_multiple_files = tk.Button(frame, text="Open Multiple Files", command=open_multiple_files, width=20)
btn_open_multiple_files.pack(pady=5, anchor="w")
btn_choose_directory = tk.Button(frame, text="Choose Directory", command=choose_directory, width=20)
btn_choose_directory.pack(pady=5, anchor="w")
# 运行主循环,使应用程序保持运行状态
root.mainloop()
tkinter选择文件和目录(filedialog)
最新推荐文章于 2024-07-10 09:15:55 发布
![](https://img-home.csdnimg.cn/images/20240709112858.png)