I'm sorry about the unclear title, I don't really know how to put it, but I am trying to make a text editor in python. I want to get the filename of a file the user open or saves in python:
def openFile():
file = filedialog.askopenfile(parent=main_window, mode='rb', title='Select a file')
contents = file.read()
textArea.delete('1.0', END)
textArea.insert('1.0', contents)
file.close()
Here the user gets an dialog to select the file he wants to open. But how can I get the filename of the file he selects?
def saveFileas():
file = filedialog.asksaveasfile(mode='w')
data = textArea.get('1.0', END+'-1c')
file.write(data)
file.close()
Here the user gets a dialog to save his file, and input the name they want. Again, I need the name the user inputs. Both are using the default windows open and save dialog.
Here is all my code:
from tkinter import Tk, scrolledtext, Menu, filedialog, END
main_window = Tk(className = " Text Editor")
textArea = scrolledtext.ScrolledText(main_window, width=100, height=80)
# def newFile():
def openFile():
file = filedialog.askopenfile(parent=main_window, mode='rb', title='Select a file')
contents = file.read()
textArea.delete('1.0', END)
textArea.insert('1.0', contents)
file.close()
def saveFileas():
file = filedialog.asksaveasfile(mode='w')
data = textArea.get('1.0', END+'-1c')
file.write(data)
file.close()
def saveFile():
content = textArea.get('1.0', END+'-1c')
if content:
print("There is content")
else:
print("There is no content")
#Menu options
menu = Menu(main_window)
main_window.config(menu=menu)
fileMenu = Menu(menu)
menu.add_cascade(label="File", menu=fileMenu)
fileMenu.add_command(label="New")
fileMenu.add_command(label="Open", command=openFile)
fileMenu.add_command(label="Save As", command=saveFileas)
fileMenu.add_command(label="Save", command=saveFile)
fileMenu.add_separator()
fileMenu.add_command(label="Print")
fileMenu.add_separator()
fileMenu.add_command(label="Exit")
textArea.pack()
main_window.mainloop()