App 5: Desktop App with Windows & Buttons / Build a notes app
Lesson 8 of 10
Open and save files
filedialog shows the normal open and save windows. Read the chosen file into the Text widget, or write the widget's contents out.
Key points
- from tkinter import filedialog
- asksaveasfilename / askopenfilename
- Handle the user pressing Cancel
from tkinter import filedialog
def save():
path = filedialog.asksaveasfilename(defaultextension=".txt")
if path:
with open(path, "w", encoding="utf-8") as f:
f.write(text.get("1.0", tk.END))Your turn
Add Open and Save to a File menu.
Quiz · +10 XP
What does asksaveasfilename return if the user presses Cancel?
Log in to save progress and earn XP.