Python Tkinter 文件对话框
Python Tkinter 文件对话框
- 文件对话框帮助我们实现可视化的操作目录、操作文件。最后,将文件、目录的信息传入到程序中。
- 文件对话框包含如下一些常用函数:
| 文件对话框 函数名 |
说明 |
|---|---|
| askopenfilename(**options) | 返回选中的文件名 |
| askopenfilenames(**options) | 返回选中的多个文件名列表 |
| askopenfile(**options) | 返回打开的文件对象 |
| askopenfiles(**options) | 返回打开的多个文件对象列表 |
| 目录对话框 函数名 |
说明 |
|---|---|
| askdirectory(**options) | 返回选中的目录名 |
| 保存对话框 函数名 |
说明 |
|---|---|
| asksaveasfile(**options) | 返回保存的文件对象 |
| asksaveasfilename(**options) | 返回保存的文件名 |
- 命名参数 options 常见值如下:
| 参数名 | 说明 |
|---|---|
| defaultextension | 默认后缀:.xxx 用户没有输入,则自动添加 |
| filetypes=[(label1, pattern1), (label2, pattern2), ... ,(labeln, patternn)] | 文件显示过滤器 按照所给定的规则过滤出文件 |
| initialdir | 初始目录;文件对话框打开最先显示的界面,如没有设置,则显示桌面文件 |
| initialfile | 初始文件 |
| parent | 父窗口,默认根窗口 |
| title | 窗口标题 |
- 【示例一】
import tkinter as tk
from tkinter.filedialog import * # 首先导入包
root = tk.Tk()
root.geometry('300x100+600+400')
def choice_file():
filename = askopenfilename(title="选择文件", initialdir="w:", filetypes=[("文本文件", ".iso")])
label['text'] = filename
tk.Button(root, text="选择文件", command=choice_file).pack()
label = tk.Label(root)
label.pack()
root.mainloop()
- 效果演示

- 【示例二】
import tkinter as tk
from tkinter.filedialog import *
root = tk.Tk()
root.geometry('300x100+600+400')
def choice_file():
with askopenfile(title="选择文件", initialdir="w:", filetypes=[("文本文件", ".txt")]) as f:
label['text'] = f.read()
tk.Button(root, text="选择文件", command=choice_file).pack()
label = tk.Label(root)
label.pack()
root.mainloop()


浙公网安备 33010602011771号