We will be using one file Menu with items ( options ) for managing file operations. Here are the items we will be including in our file menu.
New :
To create a file with default name of untitle.txt
Open :
Display the filedialog by askopefilename function asking user to select file.
Save :
Save data entered in Text widget to file, display the Save As file dialog if the file name is untitle.txt.
Save As :
File dialog to save the file as different file name.
Close:
Save the file ( above Save Operation ) and remove the content from Text widget.
Exit :
Close and exit the editor. ( With file save operation )
Layout with components of GUI
we have one Menu, One Text widget in our window. Here we have set variable init_dir to the folder we want to work. Change this path based on your system. We also declared one global variablefile_name as we will be using this variable inside different functions.
The command option executes different functions based on the required file operation. These functions are explained below.
import tkinter as tk
from tkinter import filedialog,END
from tkinter.filedialog import asksaveasfilename
my_w = tk.Tk()
my_w.geometry("409x350")
init_dir='D:\\testing\\file-menu\\' # folder to work
global file_name # global variable to store file name.
def my_fun():
pass
menubar = tk.Menu(my_w)
my_font1=('Times',12,'bold')
menu_f = tk.Menu(menubar,title='my title',tearoff=0) # file
menubar.add_cascade(label="File", menu=menu_f) # Top Line
menu_f.add_command(label="New",command=lambda:new_file())
menu_f.add_command(label="Open..",command=lambda:open_file())
menu_f.add_command(label="Save",command=lambda:save_file())
menu_f.add_command(label="Save As..",command=lambda:save_as_file())
menu_f.add_command(label="Close",command=lambda:close_file())
menu_f.add_command(label="Exit",command=my_w.quit)
my_w.config(menu=menubar) # adding menu to window
t1 = tk.Text(my_w, height=15, width=45) # added one text box
t1.grid(row=1,column=1,padx=30,pady=20)
my_w.mainloop()
new_file(): Creating new file
Inside this function the file_name value is set to untitle.txt. The title of the window is set to file_name.
def new_file():
global file_name
file_name='untitle.txt' # new file name
my_w.title(file_name) # Title of the window shows file name
open_file() : Open file
def open_file():
file = filedialog.askopenfilename(filetypes=[("txt file",".txt")],
defaultextension=".txt",initialdir=init_dir)
global file_name
file_name=file # set the file name
my_w.title(file_name) # update the GUI title
fob=open(file,'r') # open in read mode
my_str1=fob.read() # read data from file & store in variable
t1.delete('1.0',END) # remove the previous content in text box
t1.insert(tk.END, my_str1) # add new data from file to text box
fob.close()
save_file() : Save data in file
If the user has continued with the default file name untitle.txt then the function save_as_file() will be called to show file dialog to enter a new file name and save the file.
def save_file():
global file_name # collect the file name
if(file_name=='untitle.txt'): #if default file name is still there
save_as_file() # call the function
else:
fob=open(file_name,'w') # open in write mode
my_str1=t1.get("1.0",END) # collect the data from text widget
fob.write(my_str1) # write to file
save_as_file() : Saving the file in different name
This is menu item is used when user wants to store the file in different file name. So the file save dialog box will be shown to user. User may click the Cancel button, so we will check the status by using if else check and open the file in write mode to save the data.
def save_as_file():
file = filedialog.asksaveasfilename(
filetypes=[("txt file", ".txt")],
defaultextension=".txt",initialdir=init_dir)
if file: # if user has not cancelled the dialog to save
fob=open(file,'w') # open the file in write mode
my_str1=t1.get("1.0",END) # collect data from text widget
fob.write(my_str1) # write to file
my_w.title(file) # Update the GUI title with file name
fob.close() # Close file pointer
else: # user has cancelled the operation
print("No file chosen")
close_file() Close file
First we will call the function save_file() to excute the file save operation. This process can be removed if the file need not be saved while closing so last saved data will remain.
The data inside the Text widget is removed and Title of the window is kept as blank string.
def close_file():
save_file() # remove this line if not required
t1.delete('1.0',END) # remove the content from text widget
my_w.title('') # remove the title of GUI