Jan-26-2019, 03:08 AM
Hello!
I am using Tkinter and doing GUI so that there is a 'save', 'save as', and 'open' button, along with a text box.
I have got everything working except the 'save' button. I Have tried to set the name from filedialog.askopenfilename(), to a global variable to use in my 'save' function.
I have written my save function so that if the file name already exists, save over that, if not do the save_as function. It works fine when I need to save to an existing file, but when I enter straight into the text box and hit 'save' (NOT save as), it does not run the save_as function, but instead tells me that 'filename' is not defined ?
Is it saying that there is no filename because I didn't open anything ?
Is there a different want to do this that I haven't thought about ?
I cant see what I am doing wrong ? Please help!
I am using Tkinter and doing GUI so that there is a 'save', 'save as', and 'open' button, along with a text box.
I have got everything working except the 'save' button. I Have tried to set the name from filedialog.askopenfilename(), to a global variable to use in my 'save' function.
I have written my save function so that if the file name already exists, save over that, if not do the save_as function. It works fine when I need to save to an existing file, but when I enter straight into the text box and hit 'save' (NOT save as), it does not run the save_as function, but instead tells me that 'filename' is not defined ?
Is it saying that there is no filename because I didn't open anything ?
Is there a different want to do this that I haven't thought about ?
I cant see what I am doing wrong ? Please help!
def open_file(): global filename filename = filedialog.askopenfilename() ask_file= open(filename) text.insert(INSERT, ask_file.read()) return filename def save_as_file(): save_file = filedialog.asksaveasfile( mode = "w", defaultextension = '.txt') save_f = text.get(0.0, END) try: save_file.write(save_f.rstrip()) except: showerror(title = "Save Error") def save_file(): if os.path.exists(filename): save_text = text.get(0.0, END) file_save = open(filename, 'w') file_save.write(save_text) file_save.close() else: save_as_file()