tkFileDialog是具有打开和保存对话框功能的模块。 无需自己在 Tkinter GUI 中实现。
概述
文件对话框的概述:
Tkinter 打开文件
askopenfilename函数创建文件对话框对象。 扩展名显示在表格的底部(文件类型)。 下面的代码将仅显示对话框并返回文件名。 如果用户按下取消,则文件名为空。 在 Windows 计算机上,将initialdir更改为"C:\"。
Python 2.7 版本:
| 函数 | 参数 | 目的 |
|---|---|---|
.askopenfilename |
目录,标题,扩展名 | 打开文件:要求选择现有文件的对话框。 |
.asksaveasfilename |
目录,标题,扩展名 | 保存文件:要求创建或替换文件的对话框。 |
.askdirectory |
没有 | 打开目录 |
from Tkinter import *from Tkinter import *import Tkinter, Tkconstants, tkFileDialogroot = Tk()root.filename = tkFileDialog.askopenfilename(initialdir = "/",title = "Select file",filetypes = (("jpeg files","*.jpg"),("all files","*.*")))print (root.filename)
Python 3 版本:
from tkinter import filedialogfrom tkinter import *root = Tk()root.filename = filedialog.askopenfilename(initialdir = "/",title = "Select file",filetypes = (("jpeg files","*.jpg"),("all files","*.*")))print (root.filename)
这是一个示例(在 Linux 上):

Tkinter tkfiledialog askopenfilename
Tkinter 保存文件
asksaveasfilename函数使用保存文件对话框提示用户。
Python 2.7 版本
from Tkinter import *import Tkinter, Tkconstants, tkFileDialogroot = Tk()root.filename = tkFileDialog.asksaveasfilename(initialdir = "/",title = "Select file",filetypes = (("jpeg files","*.jpg"),("all files","*.*")))print (root.filename)
Python 3 版本
from tkinter import filedialogfrom tkinter import *root = Tk()root.filename = filedialog.asksaveasfilename(initialdir = "/",title = "Select file",filetypes = (("jpeg files","*.jpg"),("all files","*.*")))print (root.filename)
Tkinter 打开目录
askdirectory为用户提供了用于选择目录的弹出窗口。
Python 2.7 版本
from Tkinter import *import Tkinter, Tkconstants, tkFileDialogroot = Tk()root.directory = tkFileDialog.askdirectory()print (root.directory)

tkinter askdirectory
