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)
最新推荐文章于 2025-04-25 16:42:22 发布
本文详细介绍了使用Python的Tkinter库中的filedialog模块实现文件和目录选择功能,包括单文件选择、多文件选择以及目录选择,并展示了如何在GUI中创建相应的按钮来触发这些操作。
部署运行你感兴趣的模型镜像
您可能感兴趣的与本文相关的镜像
Python3.9
Conda
Python
Python 是一种高级、解释型、通用的编程语言,以其简洁易读的语法而闻名,适用于广泛的应用,包括Web开发、数据分析、人工智能和自动化脚本
1万+

被折叠的 条评论
为什么被折叠?



