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

Unlock This Lesson

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 Load Functionality

00:00 Adding Load Functionality As you saw previously, you now have the layout of the text editor, but it’s not functional. You’ll change that by adding the load functionality.btn_open needs to show a File Open dialog, and allow the user to select a file.

00:17 It then needs to open that file and set the text of txt_edit to the contents of the file, so it’s time to create an open file function to do this. First you import ask_open_file_name from tkinter.filedialog.

00:37 Then you create the function.

00:44 These lines use ask_open_file_name dialog from tkinter to display a file open dialog, and store the selected file to file_path.

00:57 Here you check to see if the user closes the dialog box or clicks the cancel button. If so, then file_path will be None and the function will return without executing any of the remaining code.

01:11 This clears the current contents of txt_edit using delete.

01:20 These two lines open the selected file and read the contents before storing the text as a string.

01:30 Here you assign the string text to txt_edit using insert. Finally, this line sets the title of the window so that it contains the path of the open file.

01:44 Now you can update the program so that btn_open calls open_file() whenever it’s clicked. As you saw previously, this is a case of setting the command attribute of btn_open to the open_file() function name. Save the file and run it to check that everything’s working.

02:04 You should be able to open a text file as seen on screen, and also add to the text once it’s been loaded. With this part of the application complete in the next section of the course, you’ll add the final part of the code, the save functionality.

Become a Member to join the conversation.