Saving data into a file
Apart from selecting existing files and directories, it is also possible to create a new file using Tkinter dialogs. They can be used to persist data generated by our application, letting users choose the name and location of the new file.
Getting ready
We will use the Save file
dialog to write the contents of a Text widget into a plain text file:

How to do it...
To open a dialog to save a file, we call the asksaveasfile
function from the tkinter.filedialog
module. It internally creates a file object with the 'w'
mode for writing, or None
if the dialog is dismissed:
import tkinter as tk import tkinter.filedialog as fd class App(tk.Tk): def __init__(self): super().__init__() self.text = tk.Text(self, height=10, width=50) self.btn_save = tk.Button(self, text="Save", command=self.save_file) self.text.pack() self.btn_save.pack(pady=10, ipadx=5) def save_file(self): contents = self...