Tkinter 中的文件保存对话框


我们经常使用“打开”和“保存”对话框。它们在许多应用程序中很常见,我们已经知道这些对话框的工作和行为方式。例如,如果我们点击“打开”,将会打开一个对话框来浏览文件的位置。类似地,我们有“保存”对话框。

我们可以使用 Python tkFileDialog 包创建这些对话框。为了使用该包,我们必须在我们的环境中导入它。

在笔记本中键入以下命令以导入 tkFileDialog 包:

from tkinter.filedialog import asksaveasfile


示例

在此示例中,我们将创建一个应用程序,将使用该对话框保存文件。

#Import necessary Library
from tkinter import *
from tkinter.filedialog import asksaveasfile

#Create an instance of tkinter window
win= Tk()

#Set the geometry of tkinter window
win.geometry("750x250")

#Define the function
def save_file():
   f = asksaveasfile(initialfile = 'Untitled.txt',
defaultextension=".txt",filetypes=[("All Files","*.*"),("Text Documents","*.txt")])

#Create a button
btn= Button(win, text= "Save", command= lambda:save_file())
btn.pack(pady=10)

win.mainloop()

Explore our latest online courses and learn new skills at your own pace. Enroll and become a certified expert to boost your career.

输出

在给定的代码中,我们创建了一个“保存”按钮,以使用 tkinter 中的 filedialog 模块打开保存对话框。

单击“保存”按钮以使用对话框保存文件。

更新于: 2021 年 8 月 20 日

超过 12K 的浏览量

开启你的 职业生涯

完成课程获取认证

开始学习
广告