Locked learning resources

Join us and get access to thousands of tutorials and a community of expert Pythonistas.

Unlock This Lesson

Locked learning resources

This lesson is for members only. Join us and get access to thousands of tutorials and a community of expert Pythonistas.

Unlock This Lesson

Adding Save Functionality

00:00 Adding Save Functionality. With btn_open working it’s time to work on the function for btn_save. This needs to open a Save File dialog box so that the user can choose where they would like to save the file.

00:15 You’ll use the asksaveasfilename dialog in the tkinter filedialog module for this. This function also needs to extract the text currently in txt_edit and write this to a file at the selected location.

00:31 The first thing to do is to import the asksaveasfilename function, adding it to the import line that’s already present.

00:40 Next, you create the function itself.

00:53 These lines use the asksaveasfilename dialog box to get the desired save location from the user. The selected file path is stored in the file_path variable.

01:09 Here you check to see if the user closes the dialog box or clicks the Cancel button. If so, then filepath will be None and the function will return without executing any of the remaining code within it.

01:24 This creates a new file at the selected file path.

01:30 This line extracts the text from ‘txt_edit` with the get() method and assigns it to the variable text. Here you write the text to the output_file and finally, this line updates the title of the window so that the new file path is displayed in the window title.

01:50 With this function in place, you just need to update btn_save so that it calls save_file() when it’s clicked. With all these changes made, save the file and run it.

02:04 As you can see on screen, you can enter text and then save it into a new file.

02:20 You have a minimal but fully functional text editor in under 50 lines of code. In the next section of the course, you’ll take a look back at what you’ve learned.

Become a Member to join the conversation.