In: Computer Science
Please enter flowchart. Thank you!
from tkinter import *
from tkinter.scrolledtext import ScrolledText
#method to open file and load contents into text field
def open_file():
#fetching file name from filenamevar StringVar
filename=filenamevar.get()
try:
#opening file in read mode
file=open(filename,'r')
#reading text
text=file.read()
#replacing current text in textField to read text
textField.replace("1.0",END,text)
#closing file
file.close()
except:
#displaying error message in textField
textField.replace("1.0", END, 'File not found!')
#method to save current contents of file into file mentioned in
file name entry field
def save_file():
#fetching file name
filename=filenamevar.get()
try:
#opening file in append mode
file=open(filename,'a')
#getting current text in textField
text=textField.get("1.0",END)
#writing to file
file.write(text)
#saving and closing file
file.close()
#displaying success message in textField
textField.replace("1.0",END,"Saved!")
except:
#displaying error message in textField
textField.replace("1.0", END, 'Error while saving!')
#creating a root window, setting title
root=Tk()
root.title('GUI Writer')
#creating a StringVar so it can be linked to an entry field
filenamevar=StringVar()
#creating and adding a label to the root, using grid geometry,
sticky='W' aligns west
Label(root,text='File name: ').grid(row=0,column=0,
sticky='W')
#creating Entry, linking filenamevar as textvariable. so
filenamevar can get/set
#values of entry field, sticky='EW' stretches field to fit the
column
Entry(root,textvariable=filenamevar).grid(row=0,column=1,columnspan=2,
sticky='EW')
#another label for "File contents:"
Label(root,text='File contents: ').grid(row=1,column=0,
sticky='W')
#a scrolledtext for displaying text
textField=ScrolledText(root)
#adding to root on row 2, column 0, occupying width of 4 columns
and height of 4 rows
#using a padding of 10 around margins
textField.grid(row=2,column=0, columnspan=4,
rowspan=4,padx=10,pady=10)
#creating open and save buttons, adding command to call
open_file() and save_file() methods
#respectively, for opening and saving files
Button(root,text='Open', command=open_file).grid(row=6,column=2,
sticky='EW')
Button(root,text='Save', command=save_file).grid(row=6,column=3,
sticky='EW')
#staying until user closes the window
root.mainloop()