I am using python tkinter to make a text editor. I am trying to work out the logic of how to save the file the first time with a dialog box (so you can set the file name), and all the other times without. Here is the code I have so far:
filename = ""
def save():
input_data = textinput.get("1.0", "1000000.0")
try:
with open(filename, "w") as f:
f.write(input_data)
f.close()
except IOError:
file = filedialog.asksaveasfile(initialdir="/documents", title="Save file", defaultextension=".txt", filetypes=[("HTML files", ".html"), ("All file types", ".*")])
global filename
filename = file.name
file.write(input_data)
file.close()
input_data
is the text field contents, and the save()
function is called when they push the save button.
I am trying to make it so the first time when you click save, the filename
variable has not been assigned to the file path and name, so it does the IOError, that opens the box and saves the file. It also sets a global filename
as seen here: Link. But this error is given: SyntaxError: name 'filename' is used prior to global declaration
. It is, but that is what the link said to do. How can I solve this problem? Thanks for any help in advance! xD